Class: Kward::RPC::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/rpc/server.rb

Overview

Experimental JSON-RPC backend for UI clients.

The server speaks LSP-style Content-Length framing over stdin/stdout, exposes capabilities during initialize, redacts secrets in errors and notifications, and coordinates auth, config, sessions, turns, tools, memory, commands, and startup resources.

Constant Summary collapse

PROTOCOL_VERSION =
1
JSONRPC_VERSION =
"2.0"
BUILTIN_SLASH_COMMAND_NAMES =
PromptCommands::BUILTIN_RESERVED_COMMAND_NAMES
ERROR_CODES =
{
  parse_error: -32_700,
  invalid_request: -32_600,
  method_not_found: -32_601,
  invalid_params: -32_602,
  internal_error: -32_603
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(input: $stdin, output: $stdout, error_output: $stderr, client: Client.new) ⇒ Server

Returns a new instance of Server.



38
39
40
41
42
43
44
45
# File 'lib/kward/rpc/server.rb', line 38

def initialize(input: $stdin, output: $stdout, error_output: $stderr, client: Client.new)
  @transport = Transport.new(input: input, output: output)
  @error_output = error_output
  @session_manager = SessionManager.new(server: self, client: client)
  @config_manager = ConfigManager.new
  @auth_manager = AuthManager.new(server: self, config_manager: @config_manager)
  @shutdown = false
end

Instance Method Details

#error_payload(error) ⇒ Hash

Builds redacted diagnostics suitable for JSON-RPC error data.

Parameters:

  • error (Exception)

Returns:

  • (Hash)


79
80
81
82
83
84
85
# File 'lib/kward/rpc/server.rb', line 79

def error_payload(error)
  Redactor.redact({
    code: error.class.name,
    message: error.message,
    backtrace: Array(error.backtrace).first(8)
  })
end

#log_error(error) ⇒ Object



87
88
89
# File 'lib/kward/rpc/server.rb', line 87

def log_error(error)
  @error_output.puts("Kward RPC error: #{Redactor.redact_string(error.message)}") if @error_output
end

#notify(method, params = {}) ⇒ Object

Sends a redacted JSON-RPC notification to the client.

Parameters:

  • method (String)

    notification method name

  • params (Hash) (defaults to: {})

    notification params



71
72
73
# File 'lib/kward/rpc/server.rb', line 71

def notify(method, params = {})
  @transport.write_message({ jsonrpc: JSONRPC_VERSION, method: method, params: Redactor.redact(params) })
end

#runvoid

This method returns an undefined value.

Reads framed JSON-RPC messages until shutdown or EOF.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/kward/rpc/server.rb', line 50

def run
  until @shutdown
    begin
      message = @transport.read_message
      break unless message

      handle_message(message)
    rescue JSON::ParserError => e
      write_error(nil, ERROR_CODES[:parse_error], "Parse error", e)
    rescue StandardError => e
      write_error(nil, ERROR_CODES[:invalid_request], e.message, e)
    end
  end
ensure
  @session_manager.cleanup_unused_sessions
end