Module: Smith::Tool::ScopedContext

Included in:
Smith::Tool
Defined in:
lib/smith/tool/scoped_context.rb

Constant Summary collapse

CONTEXT_KEYS =
{
  current_guardrails: :smith_tool_guardrails,
  current_deadline: :smith_tool_deadline,
  current_ledger: :smith_tool_ledger,
  current_tool_call_allowance: :smith_tool_call_allowance,
  current_tool_result_collector: :smith_tool_result_collector,
  current_invocation_context: :smith_tool_invocation_context
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.around(values, &block) ⇒ Object

Raises:

  • (ArgumentError)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/smith/tool/scoped_context.rb', line 24

def self.around(values, &block)
  raise ArgumentError, "block required" unless block

  validate!(values)
  previous = capture
  Thread.handle_interrupt(Object => :never) do
    install(values)
    begin
      Thread.handle_interrupt(Object => :immediate, &block)
    ensure
      install(previous)
    end
  end
end

.captureObject



20
21
22
# File 'lib/smith/tool/scoped_context.rb', line 20

def self.capture
  CONTEXT_KEYS.to_h { |reader, key| [reader, Thread.current[key]] }.freeze
end

Instance Method Details

#with_invocation_context(value, &block) ⇒ Object

Raises:

  • (ArgumentError)


39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/smith/tool/scoped_context.rb', line 39

def with_invocation_context(value, &block)
  raise ArgumentError, "block required" unless block

  previous = current_invocation_context
  Thread.handle_interrupt(Object => :never) do
    self.current_invocation_context = value
    begin
      Thread.handle_interrupt(Object => :immediate, &block)
    ensure
      self.current_invocation_context = previous
    end
  end
end