Class: AgentHarness::Providers::Anthropic

Inherits:
Base
  • Object
show all
Defined in:
lib/agent_harness/providers/anthropic.rb

Overview

Anthropic Claude Code CLI provider

Provides integration with the Claude Code CLI tool for AI-powered coding assistance.

Examples:

Basic usage

provider = AgentHarness::Providers::Anthropic.new
response = provider.send_message(prompt: "Hello!")

Constant Summary collapse

MODEL_PATTERN =

Model name pattern for Anthropic Claude models

/^claude-[\d.-]+-(?:opus|sonnet|haiku)(?:-\d{8})?$/i
SUPPORTED_CLI_VERSION =
"2.1.92"
SUPPORTED_CLI_REQUIREMENT =
Gem::Requirement.new(">= #{SUPPORTED_CLI_VERSION}", "< 2.2.0").freeze
VALID_VERSION_PATTERN =

Matches semver (e.g. “2.1.92”), optional pre-release (e.g. “2.1.92-beta.1”), or channel tokens (e.g. “latest”, “stable”).

/\A(?:\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?|latest|stable)\z/

Constants inherited from Base

Base::COMMON_ERROR_PATTERNS, Base::DEFAULT_SMOKE_TEST_CONTRACT

Instance Attribute Summary

Attributes inherited from Base

#config, #executor, #logger

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#configure, #initialize, #sandboxed_environment?

Methods included from Adapter

#health_status, included, metadata_package_name, normalize_metadata_installation, normalize_metadata_source_type, normalize_metadata_version_requirement, #parse_rate_limit_reset, #session_flags, #smoke_test, #smoke_test_contract, #supports_dangerous_mode?, #supports_sessions?, #validate_config, #validate_mcp_servers!

Constructor Details

This class inherits a constructor from AgentHarness::Providers::Base

Class Method Details

.available?Boolean

Returns:

  • (Boolean)


91
92
93
94
# File 'lib/agent_harness/providers/anthropic.rb', line 91

def available?
  executor = AgentHarness.configuration.command_executor
  !!executor.which(binary_name)
end

.binary_nameObject



31
32
33
# File 'lib/agent_harness/providers/anthropic.rb', line 31

def binary_name
  "claude"
end

.discover_modelsObject



129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/agent_harness/providers/anthropic.rb', line 129

def discover_models
  return [] unless available?

  begin
    require "open3"
    output, _, status = Open3.capture3("claude", "models", "list", {timeout: 10})
    return [] unless status.success?

    parse_models_list(output)
  rescue => e
    AgentHarness.logger&.debug("[AgentHarness::Anthropic] Model discovery failed: #{e.message}")
    []
  end
end

.firewall_requirementsObject



108
109
110
111
112
113
114
115
116
117
# File 'lib/agent_harness/providers/anthropic.rb', line 108

def firewall_requirements
  {
    domains: [
      "api.anthropic.com",
      "claude.ai",
      "console.anthropic.com"
    ],
    ip_ranges: []
  }
end

.install_contract(version: nil) ⇒ Object



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
# File 'lib/agent_harness/providers/anthropic.rb', line 35

def install_contract(version: nil)
  target_version = version || SUPPORTED_CLI_VERSION
  validate_version!(target_version)
  version_requirement = SUPPORTED_CLI_REQUIREMENT.requirements
    .map { |op, ver| "#{op} #{ver}" }
    .join(", ")
  channel_token = %w[latest stable].include?(target_version.to_s)

  warning = "Review the downloaded installer before execution and verify any published checksum or signature metadata when available."
  if channel_token
    warning += " Channel '#{target_version}' is not pinned; the resolved version may fall " \
      "outside the supported range (#{version_requirement}). Verify the installed version " \
      "after installation."
  end

  {
    provider: provider_name,
    binary_name: binary_name,
    binary_paths: [
      "$HOME/.local/bin/claude",
      binary_name
    ],
    install: {
      strategy: :shell,
      source: "official",
      command: "tmp_script=$(mktemp) && trap 'rm -f \"$tmp_script\"' EXIT && curl -fsSL https://claude.ai/install.sh -o \"$tmp_script\" && bash \"$tmp_script\" #{Shellwords.shellescape(target_version)}",
      warning: warning,
      post_install_binary_path: "$HOME/.local/bin/claude",
      # When a channel token is used, include the requirement so
      # consumers can validate the installed version post-install.
      version_not_pinned: channel_token
    },
    supported_versions: {
      default: SUPPORTED_CLI_VERSION,
      requirement: version_requirement,
      channel: "stable"
    },
    runtime_contract: {
      available_via: binary_name,
      build_command: [
        binary_name,
        "--print",
        "--output-format=json"
      ],
      required_features: [
        "print_mode",
        "json_output",
        "mcp_config",
        "mcp_list",
        "dangerously_skip_permissions",
        "models_list"
      ]
    }
  }
end

.instruction_file_pathsObject



119
120
121
122
123
124
125
126
127
# File 'lib/agent_harness/providers/anthropic.rb', line 119

def instruction_file_paths
  [
    {
      path: "CLAUDE.md",
      description: "Claude Code CLI agent instructions",
      symlink: true
    }
  ]
end

.model_family(provider_model_name) ⇒ Object

Normalize a provider-specific model name to its model family



145
146
147
# File 'lib/agent_harness/providers/anthropic.rb', line 145

def model_family(provider_model_name)
  provider_model_name.sub(/-\d{8}$/, "")
end

.provider_metadata_overridesObject



96
97
98
99
100
101
102
103
104
105
106
# File 'lib/agent_harness/providers/anthropic.rb', line 96

def 
  {
    auth: {
      service: :anthropic,
      api_family: :anthropic
    },
    identity: {
      bot_usernames: %w[claude anthropic]
    }
  }
end

.provider_model_name(family_name) ⇒ Object

Convert a model family name to the provider’s preferred model name



150
151
152
# File 'lib/agent_harness/providers/anthropic.rb', line 150

def provider_model_name(family_name)
  family_name
end

.provider_nameObject



27
28
29
# File 'lib/agent_harness/providers/anthropic.rb', line 27

def provider_name
  :claude
end

.smoke_test_contractObject



159
160
161
# File 'lib/agent_harness/providers/anthropic.rb', line 159

def smoke_test_contract
  Base::DEFAULT_SMOKE_TEST_CONTRACT
end

.supports_model_family?(family_name) ⇒ Boolean

Check if this provider supports a given model family

Returns:

  • (Boolean)


155
156
157
# File 'lib/agent_harness/providers/anthropic.rb', line 155

def supports_model_family?(family_name)
  MODEL_PATTERN.match?(family_name)
end

Instance Method Details

#auth_typeObject



315
316
317
# File 'lib/agent_harness/providers/anthropic.rb', line 315

def auth_type
  :oauth
end

#build_mcp_flags(mcp_servers, working_dir: nil) ⇒ Object



304
305
306
307
308
309
# File 'lib/agent_harness/providers/anthropic.rb', line 304

def build_mcp_flags(mcp_servers, working_dir: nil)
  return [] if mcp_servers.empty?

  config_path = write_mcp_config_file(mcp_servers, working_dir: working_dir)
  ["--mcp-config", config_path]
end

#capabilitiesObject



278
279
280
281
282
283
284
285
286
287
288
# File 'lib/agent_harness/providers/anthropic.rb', line 278

def capabilities
  {
    streaming: true,
    file_upload: true,
    vision: true,
    tool_use: true,
    json_mode: true,
    mcp: true,
    dangerous_mode: true
  }
end

#configuration_schemaObject



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/agent_harness/providers/anthropic.rb', line 261

def configuration_schema
  {
    fields: [
      {
        name: :model,
        type: :string,
        label: "Model",
        required: false,
        hint: "Claude model to use (e.g. claude-3-5-sonnet-20241022)",
        accepts_arbitrary: false
      }
    ],
    auth_modes: [:oauth],
    openai_compatible: false
  }
end

#dangerous_mode_flagsObject



311
312
313
# File 'lib/agent_harness/providers/anthropic.rb', line 311

def dangerous_mode_flags
  ["--dangerously-skip-permissions"]
end

#display_nameObject



257
258
259
# File 'lib/agent_harness/providers/anthropic.rb', line 257

def display_name
  "Anthropic Claude CLI"
end

#error_patternsObject



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
# File 'lib/agent_harness/providers/anthropic.rb', line 332

def error_patterns
  {
    rate_limited: [
      /rate.?limit/i,
      /too.?many.?requests/i,
      /429/,
      /overloaded/i,
      /session.?limit/i
    ],
    auth_expired: [
      /oauth.*token.*expired/i,
      /authentication.*error/i,
      /invalid.*api.*key/i,
      /unauthorized/i,
      /401/,
      /session.*expired/i,
      /not.*logged.*in/i,
      /login.*required/i,
      /credentials.*expired/i
    ],
    quota_exceeded: [
      /quota.*exceeded/i,
      /usage.*limit/i,
      /credit.*exhausted/i
    ],
    transient: [
      /timeout/i,
      /connection.*reset/i,
      /temporary.*error/i,
      /service.*unavailable/i,
      /503/,
      /502/,
      /504/
    ],
    permanent: [
      /invalid.*model/i,
      /unsupported.*operation/i,
      /not.*found/i,
      /404/,
      /bad.*request/i,
      /400/,
      /model.*deprecated/i,
      /end-of-life/i
    ]
  }
end

#execution_semanticsObject



319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/agent_harness/providers/anthropic.rb', line 319

def execution_semantics
  {
    prompt_delivery: :arg,
    output_format: :json,
    sandbox_aware: true,
    uses_subcommand: false,
    non_interactive_flag: "--print",
    legitimate_exit_codes: [0],
    stderr_is_diagnostic: true,
    parses_rate_limit_reset: false
  }
end

#fetch_mcp_serversObject



379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/agent_harness/providers/anthropic.rb', line 379

def fetch_mcp_servers
  return [] unless self.class.available?

  begin
    result = @executor.execute(["claude", "mcp", "list"], timeout: 5)
    return [] unless result.success?

    parse_claude_mcp_output(result.stdout)
  rescue => e
    log_debug("fetch_mcp_servers_failed", error: e.message)
    []
  end
end

#nameObject



253
254
255
# File 'lib/agent_harness/providers/anthropic.rb', line 253

def name
  "anthropic"
end

#send_message(prompt:, **options) ⇒ Object



290
291
292
293
294
# File 'lib/agent_harness/providers/anthropic.rb', line 290

def send_message(prompt:, **options)
  super
ensure
  cleanup_mcp_tempfiles!
end

#supported_mcp_transportsObject



300
301
302
# File 'lib/agent_harness/providers/anthropic.rb', line 300

def supported_mcp_transports
  %w[stdio http sse]
end

#supports_mcp?Boolean

Returns:

  • (Boolean)


296
297
298
# File 'lib/agent_harness/providers/anthropic.rb', line 296

def supports_mcp?
  true
end