Class: Agent::SessionContext::SessionResolver

Inherits:
Object
  • Object
show all
Defined in:
lib/agent/session_context/session_resolver.rb

Constant Summary collapse

SUPPORTED =
%i[claude codex].freeze

Instance Method Summary collapse

Constructor Details

#initialize(catalog: Agent::Sessions, env: ENV) ⇒ SessionResolver

Returns a new instance of SessionResolver.



8
9
10
11
# File 'lib/agent/session_context/session_resolver.rb', line 8

def initialize(catalog: Agent::Sessions, env: ENV)
  @catalog = catalog
  @env = env
end

Instance Method Details

#current(agent: nil) ⇒ Object



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
# File 'lib/agent/session_context/session_resolver.rb', line 31

def current(agent: nil, &)
  generic_identifier = fetch_env("AGENT_SESSION_ID")
  if present?(generic_identifier)
    agent_name = fetch_env("AGENT_NAME")
    unless present?(agent_name)
      raise CurrentSessionUnavailable,
            "AGENT_SESSION_ID is set but AGENT_NAME is missing."
    end

    return resolve(generic_identifier, agent: normalize_agent(agent_name, source: "AGENT_NAME"))
  end

  claude_identifier = fetch_env("CLAUDE_CODE_SESSION_ID")
  codex_identifier = current_codex_identifier

  if present?(claude_identifier) && present?(codex_identifier)
    codex_source = present?(fetch_env("CODEX_SESSION_ID")) ? "CODEX_SESSION_ID" : "CODEX_THREAD_ID"
    raise CurrentSessionUnavailable,
          "Conflicting current session variables: CLAUDE_CODE_SESSION_ID and " \
          "#{codex_source}. Clear one and retry."
  end

  return resolve(claude_identifier, agent: :claude) if present?(claude_identifier)
  return resolve(codex_identifier, agent: :codex) if present?(codex_identifier)

  current_from_disk(agent:, &)
end

#resolve(identifier, agent: nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/agent/session_context/session_resolver.rb', line 13

def resolve(identifier, agent: nil)
  parsed_agent, session_id = parse_identifier(identifier)
  requested_agent = (agent && normalize_agent(agent, source: "agent")) || parsed_agent

  return resolve_for_agent(requested_agent, session_id) if requested_agent

  matches = SUPPORTED.flat_map do |candidate|
    matching_sessions(candidate, session_id)
  end

  resolve_cardinality(
    matches,
    not_found_message: "Session #{session_id.inspect} was not found for claude or codex.",
    ambiguous_message: "Session #{session_id.inspect} matches multiple sessions: " \
                       "#{matches.map(&:uid).join(", ")}. Use an exact agent-prefixed identifier."
  )
end