praxo-core 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 74d95fdeec16986125998ec61ddb5540ab93f070b6694a00e571876c08b4cd0d
4
- data.tar.gz: 991756d2d1fd4c96e9bf968a587715b3e134104f47d466b2655d957fc2908456
3
+ metadata.gz: 4975c4a8d241b094789de25f7bf80ab08b442d154abb816c7bb54b30c5400784
4
+ data.tar.gz: d43f996a431634a84484de307d0dd4668e8052d99d61c2f8fdc7853683e51760
5
5
  SHA512:
6
- metadata.gz: 0207b3521c72bfeaeb286f0ba59b11f462a2da1e00c9b14d729898da3922e11833735bb4b224037469818422b17cb8244108c922aa7f251447816e5b14503df1
7
- data.tar.gz: 84b8492473685ddc9f16ca7832d63126476b47577d76f049e5f19fc32932bc2237db98eaef16291fe419908eb10d028c196c23b1c4fdc3f89900a67adf8f7e84
6
+ metadata.gz: a9f62729753be864c1bf4f19cc8fa1536f418944efb39d81cf43c0c10e9066a737132bbe64465ea1a3a4434c9adca191678f05a011543da64e7339dc178f9818
7
+ data.tar.gz: 6117c0418bb0e50d88683ef9bbbdc6d836f18d48cb3b167f5410dc35a7c05d83914dc84a95805a69f2f5a71b8258000a26d4b299fcb9c1124d278f6cd0dedb10
data/README.md CHANGED
@@ -14,7 +14,14 @@ reference implementation.
14
14
  - License: MIT
15
15
  - Dependencies: Ruby standard library only
16
16
  - Ruby source repository: https://github.com/axisvela/praxo-core-ruby
17
- - The latest RubyGems package is `praxo-core@0.4.0`
17
+ - The latest RubyGems package is `praxo-core@0.4.1`
18
+
19
+ ## Registry and Coding-Agent Entry
20
+
21
+ - Registry introduction: [REGISTRY.md](https://github.com/axisvela/praxo-core/blob/main/language/ruby/REGISTRY.md)
22
+ - Machine-readable entry: [llms.txt](https://github.com/axisvela/praxo-core/blob/main/language/ruby/llms.txt) and [llms.md](https://github.com/axisvela/praxo-core/blob/main/language/ruby/llms.md)
23
+ - Coding-agent contract: [docs/getting-started/coding-agents.md](https://github.com/axisvela/praxo-core/blob/main/docs/getting-started/coding-agents.md)
24
+ - Registry: [RubyGems](https://rubygems.org/gems/praxo-core/versions/0.4.1)
18
25
 
19
26
  ## Install
20
27
 
@@ -81,6 +88,41 @@ execution, and run-scoped call limits:
81
88
  `Praxo::SSE.parse` parses OpenAI-compatible server-sent-event text and raises
82
89
  `MODEL_STREAM` for truncated streams or malformed half packets.
83
90
 
91
+ ## Model Adapters
92
+
93
+ - `Praxo::Adapters::OpenAICompatible` for OpenAI, DeepSeek, Kimi/Moonshot, and
94
+ other OpenAI-compatible endpoints.
95
+ - `Praxo::Adapters::Anthropic` for the Anthropic Messages API.
96
+ - `Praxo::Adapters::Gemini` for the Gemini generateContent API.
97
+
98
+ Each adapter accepts a `transport` lambda for deterministic tests.
99
+
100
+ ## MCP Client
101
+
102
+ `Praxo::Adapters::MCPClient` implements a stdio JSON-RPC MCP session with
103
+ initialize, paginated tool listing, tool calls, timeouts, and cancellation
104
+ notifications. Pass `reader`/`writer` to inject a deterministic transport, or
105
+ provide `command:` to start a child process with `Open3`.
106
+
107
+ ## Harmovela Event Sink
108
+
109
+ `Praxo::Adapters::HarmovelaSink` posts each event to `{base_url}/events` with an
110
+ `application/json` envelope. Inject `transport` and `clock` for deterministic
111
+ tests.
112
+
113
+ ```ruby
114
+ sink = Praxo::Adapters::HarmovelaSink.new(
115
+ base_url: 'http://127.0.0.1:8790/aep/api',
116
+ source: 'praxo-core'
117
+ )
118
+ options.events = sink
119
+ ```
120
+
121
+ A 2xx response is success; any other status raises `HARMOVELA_HTTP` with the
122
+ status and a bounded body. The sink adds no authentication, retries, buffering,
123
+ ordering, or exactly-once delivery. Use HTTPS and filter sensitive event data
124
+ before emitting.
125
+
84
126
  ## Layout
85
127
 
86
128
  - `lib/praxo/` package source.
data/REGISTRY.md ADDED
@@ -0,0 +1,42 @@
1
+ # PRAXO-CORE Ruby Registry Introduction
2
+
3
+ **Status:** published; split source repository. Source version `0.5.0`, source
4
+ tag `ruby/v0.5.0`. Published registry version: `0.4.1`. Registry
5
+ pages are release snapshots; verify the published version before relying on a
6
+ feature.
7
+
8
+ ## Positioning
9
+
10
+ PRAXO-CORE is an embeddable, MIT-licensed agent framework. This gem is its native Ruby Core: an agent loop with tool registration and dispatch, policy hooks, typed events, memory, checkpoints, context budgets, middleware, JSON Schema validation, and plugin manifest parsing.
11
+
12
+ ## Package
13
+
14
+ | Field | Value |
15
+ | --- | --- |
16
+ | Package | `praxo-core` |
17
+ | Registry | [RubyGems](https://rubygems.org/gems/praxo-core/versions/0.4.1) |
18
+ | Source version | `0.5.0` |
19
+ | Published registry version | `0.4.1` |
20
+ | Install (published) | `gem install praxo-core` |
21
+ | Install (source/release prepared) | `gem install praxo-core` |
22
+ | Source tag | `ruby/v0.5.0` |
23
+ | Tier | Core |
24
+ | Contract | `SPEC_VERSION` `0.2.0` |
25
+ | Documentation | https://axisvela.github.io/praxo-core/languages/ruby/ |
26
+
27
+ ## Coding-agent entry
28
+
29
+ - [llms.txt](llms.txt): compact machine-readable entry for this language.
30
+ - [llms.md](llms.md): Markdown version of the same entry.
31
+ - [Coding-agent contract](../../docs/getting-started/coding-agents.md): explicit
32
+ scope, final-argument authorization, denial tests, and verification commands.
33
+
34
+ ## Boundaries
35
+
36
+ - PRAXO-CORE is an embeddable, MIT-licensed execution kernel, not a hosted
37
+ model, workflow engine, identity provider, or safety controller.
38
+ - Do not infer exactly-once execution, complete sandbox isolation, production
39
+ security certification, live-provider behavior, or physical safety from this
40
+ package.
41
+ - Check the registry page and source tag for the exact version; source READMEs
42
+ and canonical documentation may be newer than a published registry page.
data/api/0.5.0.txt ADDED
@@ -0,0 +1,122 @@
1
+ # PRAXO-CORE Ruby API 0.5.0
2
+ # SPEC_VERSION 0.2.0
3
+
4
+ class AgentOptions
5
+ class CallLimit
6
+ class CheckpointAllowlist
7
+ class ContextBudget
8
+ class Error
9
+ class FilterSink
10
+ class FuncTool
11
+ class MemoryStore
12
+ class MultiSink
13
+ class PathChecker
14
+ class PiiRedactor
15
+ class Runner
16
+ class StaticModel
17
+ class StructuredOutput
18
+ class ToolRegistry
19
+ class ToolSelection
20
+ def action
21
+ def after_run
22
+ def allowed?
23
+ def allows?
24
+ def apply
25
+ def apply_interrupt
26
+ def array
27
+ def as_int
28
+ def as_object
29
+ def as_string
30
+ def authorize
31
+ def before_model
32
+ def before_run
33
+ def before_tool
34
+ def bool
35
+ def check
36
+ def check_cancelled
37
+ def check_enum
38
+ def check_keys
39
+ def compact
40
+ def content_block
41
+ def decision
42
+ def emit
43
+ def emit_stream
44
+ def equals
45
+ def error
46
+ def error_code
47
+ def estimate_tokens
48
+ def event
49
+ def execute_tool
50
+ def extract_json
51
+ def fallback_model
52
+ def filter
53
+ def generate
54
+ def get
55
+ def has?
56
+ def initialize
57
+ def int
58
+ def interrupt
59
+ def interrupt_decision
60
+ def invoke
61
+ def invoke_tool
62
+ def invoke_tools
63
+ def marshal
64
+ def memory_record
65
+ def message
66
+ def message_assistant
67
+ def message_text
68
+ def message_tool
69
+ def message_wire
70
+ def parse
71
+ def parse_input_json
72
+ def parse_json_call
73
+ def parse_manifest
74
+ def parse_plain
75
+ def parse_tag
76
+ def parse_toolcall
77
+ def parse_xml
78
+ def plus
79
+ def prepare_tool
80
+ def put
81
+ def redact
82
+ def redact_value
83
+ def register
84
+ def reject
85
+ def request
86
+ def resolve_path
87
+ def response
88
+ def run
89
+ def run_agent
90
+ def run_result
91
+ def search
92
+ def session
93
+ def specs
94
+ def stream_part
95
+ def string
96
+ def stringify
97
+ def strip_markup
98
+ def structured_apply
99
+ def text_present
100
+ def tool_call
101
+ def tool_spec
102
+ def truncate_to_tokens
103
+ def unmarshal
104
+ def usage
105
+ def validate
106
+ def visit
107
+ def visit_array
108
+ def visit_boolean
109
+ def visit_number
110
+ def visit_object
111
+ def visit_string
112
+ def within?
113
+ module Agent
114
+ module Json
115
+ module JsonSchema
116
+ module Middleware
117
+ module Models
118
+ module Plugin
119
+ module Praxo
120
+ module Runtime
121
+ module SSE
122
+ module Toolcall
@@ -0,0 +1,172 @@
1
+ require 'net/http'
2
+ require 'uri'
3
+ require_relative '../models'
4
+ require_relative '../json'
5
+ require_relative '../errors'
6
+
7
+ module Praxo
8
+ module Adapters
9
+ # Anthropic Messages adapter with an injectable transport.
10
+ class Anthropic
11
+ DEFAULT_BASE_URL = 'https://api.anthropic.com'
12
+ DEFAULT_VERSION = '2023-06-01'
13
+
14
+ def initialize(base_url: DEFAULT_BASE_URL, model:, api_key: nil, version: DEFAULT_VERSION,
15
+ max_tokens: 1024, transport: nil, timeout: 60)
16
+ @base_url = base_url.to_s.sub(%r{/$}, '')
17
+ @model = model
18
+ @api_key = api_key
19
+ @version = version
20
+ @max_tokens = max_tokens
21
+ @transport = transport
22
+ @timeout = timeout
23
+ end
24
+
25
+ def generate(request)
26
+ Praxo.error('MODEL_CONFIG', 'anthropic: API key is required') unless @api_key && !@api_key.empty?
27
+ Praxo.error('MODEL_CONFIG', 'anthropic: model is required') unless @model && !@model.empty?
28
+
29
+ payload = build_payload(request)
30
+ data = @transport ? @transport.call('/v1/messages', payload) : post(payload)
31
+ parse_response(data)
32
+ end
33
+
34
+ private
35
+
36
+ def build_payload(request)
37
+ system, messages = build_messages(request.messages)
38
+ payload = {
39
+ model: @model,
40
+ max_tokens: @max_tokens,
41
+ messages: messages
42
+ }
43
+ payload[:system] = system unless system.empty?
44
+ tools = Array(request.tools).map do |tool|
45
+ {
46
+ name: tool.name,
47
+ description: tool.description,
48
+ input_schema: tool.parameters || { type: 'object', properties: {} }
49
+ }
50
+ end
51
+ unless tools.empty?
52
+ payload[:tools] = tools
53
+ choice = tool_choice(request.tool_choice)
54
+ payload[:tool_choice] = choice if choice
55
+ end
56
+ payload[:temperature] = request.temperature if request.temperature
57
+ payload
58
+ end
59
+
60
+ def build_messages(messages)
61
+ system = []
62
+ out = []
63
+ pending = []
64
+ flush = lambda do
65
+ unless pending.empty?
66
+ out << { role: 'user', content: pending.dup }
67
+ pending.clear
68
+ end
69
+ end
70
+ Array(messages).each do |message|
71
+ if message.role == Models::SYSTEM
72
+ system << message.content if message.content && !message.content.empty?
73
+ next
74
+ end
75
+ if message.role == Models::TOOL
76
+ pending << {
77
+ type: 'tool_result',
78
+ tool_use_id: message.tool_id || '',
79
+ content: message.content || ''
80
+ }
81
+ next
82
+ end
83
+ flush.call
84
+ content = message_content(message)
85
+ out << { role: message.role, content: content } unless content.empty?
86
+ end
87
+ flush.call
88
+ [system.join("\n\n"), out]
89
+ end
90
+
91
+ def message_content(message)
92
+ content = []
93
+ content << { type: 'text', text: message.content } if message.content && !message.content.empty?
94
+ Array(message.content_blocks).each do |block|
95
+ if block.type == 'text' && block.text && !block.text.empty?
96
+ content << { type: 'text', text: block.text }
97
+ end
98
+ end
99
+ Array(message.tool_calls).each do |call|
100
+ content << {
101
+ type: 'tool_use',
102
+ id: call.id,
103
+ name: call.name,
104
+ input: call.arguments || {}
105
+ }
106
+ end
107
+ content
108
+ end
109
+
110
+ def tool_choice(choice)
111
+ case choice
112
+ when 'auto' then { type: 'auto' }
113
+ when 'required' then { type: 'any' }
114
+ when 'none' then { type: 'none' }
115
+ end
116
+ end
117
+
118
+ def parse_response(data)
119
+ Praxo.error('MODEL_HTTP', "anthropic: #{data['error']['message']}") if data['error']
120
+
121
+ text = +''
122
+ calls = []
123
+ Array(data['content']).each do |block|
124
+ case block['type']
125
+ when 'text'
126
+ text << block['text'].to_s
127
+ when 'tool_use'
128
+ calls << Models.tool_call(
129
+ id: block['id'] || "call-#{calls.length + 1}",
130
+ name: block['name'] || '',
131
+ arguments: block['input'] || {}
132
+ )
133
+ end
134
+ end
135
+ usage = data['usage'] || {}
136
+ Models.response(
137
+ message: Models.message(
138
+ role: Models::ASSISTANT,
139
+ content: text,
140
+ tool_calls: calls
141
+ ),
142
+ usage: Models.usage(
143
+ input_tokens: usage['input_tokens'].to_i,
144
+ output_tokens: usage['output_tokens'].to_i,
145
+ cached_tokens: usage['cache_read_input_tokens'].to_i
146
+ ),
147
+ finish_reason: data['stop_reason']
148
+ )
149
+ end
150
+
151
+ def post(payload)
152
+ uri = URI.join(@base_url + '/', 'v1/messages')
153
+ request = Net::HTTP::Post.new(uri)
154
+ request['Content-Type'] = 'application/json'
155
+ request['x-api-key'] = @api_key
156
+ request['anthropic-version'] = @version
157
+ request.body = Json.stringify(payload)
158
+ response = Net::HTTP.start(
159
+ uri.host,
160
+ uri.port,
161
+ use_ssl: uri.scheme == 'https',
162
+ read_timeout: @timeout
163
+ ) { |http| http.request(request) }
164
+ body = response.body.to_s
165
+ unless response.is_a?(Net::HTTPSuccess)
166
+ Praxo.error('PROVIDER_HTTP', "provider returned HTTP #{response.code}: #{body}")
167
+ end
168
+ Json.parse(body)
169
+ end
170
+ end
171
+ end
172
+ end
@@ -0,0 +1,179 @@
1
+ require 'net/http'
2
+ require 'uri'
3
+ require_relative '../models'
4
+ require_relative '../json'
5
+
6
+ module Praxo
7
+ module Adapters
8
+ # Gemini generateContent adapter with an injectable transport.
9
+ class Gemini
10
+ DEFAULT_BASE_URL = 'https://generativelanguage.googleapis.com'
11
+
12
+ def initialize(base_url: DEFAULT_BASE_URL, model:, api_key: nil,
13
+ max_output_tokens: 0, transport: nil, timeout: 60)
14
+ @base_url = base_url.to_s.sub(%r{/$}, '')
15
+ @model = model
16
+ @api_key = api_key
17
+ @max_output_tokens = max_output_tokens
18
+ @transport = transport
19
+ @timeout = timeout
20
+ end
21
+
22
+ def generate(request)
23
+ Praxo.error('MODEL_CONFIG', 'gemini: API key is required') unless @api_key && !@api_key.empty?
24
+ Praxo.error('MODEL_CONFIG', 'gemini: model is required') unless @model && !@model.empty?
25
+
26
+ payload = build_payload(request)
27
+ path = "/v1beta/models/#{URI.encode_www_form_component(@model)}:generateContent"
28
+ data = @transport ? @transport.call(path, payload) : post(path, payload)
29
+ parse_response(data)
30
+ end
31
+
32
+ private
33
+
34
+ def build_payload(request)
35
+ system, contents = build_contents(request.messages)
36
+ payload = { contents: contents }
37
+ payload[:system_instruction] = { parts: system } unless system.empty?
38
+ tools = Array(request.tools).map do |tool|
39
+ {
40
+ name: tool.name,
41
+ description: tool.description,
42
+ parameters: tool.parameters || { type: 'object', properties: {} }
43
+ }
44
+ end
45
+ unless tools.empty?
46
+ payload[:tools] = [{ functionDeclarations: tools }]
47
+ payload[:toolConfig] = {
48
+ functionCallingConfig: { mode: tool_mode(request.tool_choice) }
49
+ }
50
+ end
51
+ if (request.temperature && request.temperature != 0) || @max_output_tokens.to_i.positive?
52
+ payload[:generationConfig] = {
53
+ temperature: request.temperature || 0,
54
+ maxOutputTokens: @max_output_tokens
55
+ }
56
+ end
57
+ payload
58
+ end
59
+
60
+ def build_contents(messages)
61
+ system = []
62
+ out = []
63
+ pending = []
64
+ names = {}
65
+ flush = lambda do
66
+ unless pending.empty?
67
+ out << { role: 'user', parts: pending.dup }
68
+ pending.clear
69
+ end
70
+ end
71
+ Array(messages).each do |message|
72
+ if message.role == Models::SYSTEM
73
+ system << { text: message.content } if message.content && !message.content.empty?
74
+ next
75
+ end
76
+ if message.role == Models::TOOL
77
+ name = names[message.tool_id] || message.tool_id || 'tool'
78
+ pending << {
79
+ functionResponse: {
80
+ name: name,
81
+ response: { result: message.content || '' }
82
+ }
83
+ }
84
+ next
85
+ end
86
+ flush.call
87
+ parts = message_parts(message)
88
+ unless parts.empty?
89
+ out << {
90
+ role: message.role == Models::ASSISTANT ? 'model' : 'user',
91
+ parts: parts
92
+ }
93
+ end
94
+ Array(message.tool_calls).each do |call|
95
+ names[call.id] = call.name if call.id && !call.id.empty? && call.name && !call.name.empty?
96
+ end
97
+ end
98
+ flush.call
99
+ [system, out]
100
+ end
101
+
102
+ def message_parts(message)
103
+ parts = []
104
+ parts << { text: message.content } if message.content && !message.content.empty?
105
+ Array(message.content_blocks).each do |block|
106
+ if block.type == 'text' && block.text && !block.text.empty?
107
+ parts << { text: block.text }
108
+ end
109
+ end
110
+ Array(message.tool_calls).each do |call|
111
+ parts << { functionCall: { name: call.name, args: call.arguments || {} } }
112
+ end
113
+ parts
114
+ end
115
+
116
+ def tool_mode(choice)
117
+ case choice
118
+ when 'required' then 'ANY'
119
+ when 'none' then 'NONE'
120
+ else 'AUTO'
121
+ end
122
+ end
123
+
124
+ def parse_response(data)
125
+ Praxo.error('MODEL_HTTP', "gemini: #{data['error']['message']}") if data['error']
126
+
127
+ candidate = Array(data['candidates']).first
128
+ Praxo.error('MODEL_HTTP', 'gemini: empty response') unless candidate
129
+
130
+ text = +''
131
+ calls = []
132
+ Array((candidate['content'] || {})['parts']).each do |part|
133
+ text << part['text'].to_s if part['text']
134
+ call = part['functionCall']
135
+ next unless call
136
+
137
+ calls << Models.tool_call(
138
+ id: "call-#{calls.length + 1}",
139
+ name: call['name'] || '',
140
+ arguments: call['args'] || {}
141
+ )
142
+ end
143
+ usage = data['usageMetadata'] || {}
144
+ Models.response(
145
+ message: Models.message(
146
+ role: Models::ASSISTANT,
147
+ content: text,
148
+ tool_calls: calls
149
+ ),
150
+ usage: Models.usage(
151
+ input_tokens: usage['promptTokenCount'].to_i,
152
+ output_tokens: usage['candidatesTokenCount'].to_i,
153
+ cached_tokens: usage['cachedContentTokenCount'].to_i
154
+ ),
155
+ finish_reason: candidate['finishReason']
156
+ )
157
+ end
158
+
159
+ def post(path, payload)
160
+ uri = URI.join(@base_url + '/', path.sub(%r{^/}, ''))
161
+ request = Net::HTTP::Post.new(uri)
162
+ request['Content-Type'] = 'application/json'
163
+ request['x-goog-api-key'] = @api_key
164
+ request.body = Json.stringify(payload)
165
+ response = Net::HTTP.start(
166
+ uri.host,
167
+ uri.port,
168
+ use_ssl: uri.scheme == 'https',
169
+ read_timeout: @timeout
170
+ ) { |http| http.request(request) }
171
+ body = response.body.to_s
172
+ unless response.is_a?(Net::HTTPSuccess)
173
+ Praxo.error('PROVIDER_HTTP', "provider returned HTTP #{response.code}: #{body}")
174
+ end
175
+ Json.parse(body)
176
+ end
177
+ end
178
+ end
179
+ end
@@ -0,0 +1,73 @@
1
+ require 'net/http'
2
+ require 'uri'
3
+ require_relative '../errors'
4
+ require_relative '../json'
5
+
6
+ module Praxo
7
+ module Adapters
8
+ class HarmovelaSink
9
+ MAX_BODY = 1024
10
+
11
+ def initialize(base_url:, source: nil, spec_version: nil, transport: nil, clock: nil, timeout: 10)
12
+ @base_url = base_url.to_s.sub(%r{/+\z}, '')
13
+ @source = source || 'praxo-core'
14
+ @spec_version = spec_version || '0.2'
15
+ @transport = transport
16
+ @clock = clock || -> { Time.now.utc }
17
+ @timeout = timeout
18
+ end
19
+
20
+ def emit(event)
21
+ Praxo.error('HARMOVELA_URL', 'harmovela: base URL is required') if @base_url.empty?
22
+ at = @clock.call.utc
23
+ payload = (event.data || {}).dup
24
+ if event.session_id && !event.session_id.empty?
25
+ payload['session_id'] = event.session_id
26
+ end
27
+ payload['run_id'] = event.run_id if event.run_id && !event.run_id.empty?
28
+ envelope = {
29
+ 'spec_version' => @spec_version,
30
+ 'id' => event_id(event, at),
31
+ 'type' => event.type,
32
+ 'source' => @source,
33
+ 'created_at' => created_at(at),
34
+ 'payload' => payload
35
+ }
36
+ body = Json.stringify(envelope)
37
+ headers = { 'content-type' => 'application/json' }
38
+ status, response_body = @transport ? @transport.call('/events', body, headers) : post(body, headers)
39
+ return if status.to_i >= 200 && status.to_i < 300
40
+
41
+ bounded = response_body.to_s[0, MAX_BODY]
42
+ Praxo.error('HARMOVELA_HTTP', "harmovela: HTTP #{status}: #{bounded}")
43
+ end
44
+
45
+ private
46
+
47
+ def event_id(event, at)
48
+ prefix = event.run_id
49
+ prefix = event.session_id if prefix.nil? || prefix.empty?
50
+ prefix = 'event' if prefix.nil? || prefix.empty?
51
+ "#{prefix}-#{at.to_i * 1_000_000_000 + at.nsec}"
52
+ end
53
+
54
+ def created_at(at)
55
+ "#{at.strftime('%Y-%m-%dT%H:%M:%S')}.#{format('%09d', at.nsec)}Z"
56
+ end
57
+
58
+ def post(body, headers)
59
+ uri = URI.parse(@base_url + '/events')
60
+ request = Net::HTTP::Post.new(uri)
61
+ headers.each { |key, value| request[key] = value }
62
+ request.body = body
63
+ response = Net::HTTP.start(
64
+ uri.host,
65
+ uri.port,
66
+ use_ssl: uri.scheme == 'https',
67
+ read_timeout: @timeout
68
+ ) { |http| http.request(request) }
69
+ [response.code.to_i, response.body.to_s]
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,178 @@
1
+ require 'json'
2
+ require 'open3'
3
+ require 'timeout'
4
+
5
+ module Praxo
6
+ module Adapters
7
+ # Minimal MCP stdio JSON-RPC client.
8
+ class MCPClient
9
+ DEFAULT_PROTOCOL_VERSION = '2024-11-05'
10
+
11
+ attr_reader :protocol_version, :server_info
12
+
13
+ def initialize(command: nil, args: [], env: {}, timeout: 5, reader: nil, writer: nil)
14
+ @command = command
15
+ @args = args
16
+ @env = env
17
+ @timeout = timeout
18
+ @reader = reader
19
+ @writer = writer
20
+ @next_id = 0
21
+ @closed = false
22
+ @connected = false
23
+ end
24
+
25
+ def start
26
+ return self if @connected
27
+
28
+ if @reader.nil? || @writer.nil?
29
+ raise Praxo::Error.new('MCP_TRANSPORT', 'mcp: command is required') if @command.nil?
30
+
31
+ @stdin, @stdout, @stderr, @wait = Open3.popen3(@env, @command, *@args)
32
+ @writer = @stdin
33
+ @reader = @stdout
34
+ end
35
+ result = request('initialize', {
36
+ protocolVersion: DEFAULT_PROTOCOL_VERSION,
37
+ capabilities: {},
38
+ clientInfo: { name: 'praxo-core', version: '0.5.0' }
39
+ })
40
+ version = result.is_a?(Hash) ? result['protocolVersion'] : nil
41
+ if version.nil? || version.empty?
42
+ raise Praxo::Error.new('MCP_HANDSHAKE', 'mcp: initialize returned no protocol version')
43
+ end
44
+ @protocol_version = version
45
+ @server_info = result['serverInfo'] || {}
46
+ notify('notifications/initialized', {})
47
+ @connected = true
48
+ self
49
+ end
50
+
51
+ def list_tools
52
+ ensure_connected!
53
+ tools = []
54
+ names = {}
55
+ cursor = nil
56
+ seen_cursors = {}
57
+ loop do
58
+ params = cursor.nil? ? {} : { cursor: cursor }
59
+ result = request('tools/list', params)
60
+ list = result.is_a?(Hash) ? Array(result['tools']) : []
61
+ list.each do |tool|
62
+ name = tool['name'].to_s
63
+ raise Praxo::Error.new('MCP_DUPLICATE_TOOL', "mcp: duplicate tool #{name}") if names[name]
64
+ names[name] = true
65
+ tools << tool
66
+ end
67
+ cursor = result['nextCursor'] if result.is_a?(Hash)
68
+ break if cursor.nil? || cursor.to_s.empty?
69
+ if seen_cursors[cursor]
70
+ raise Praxo::Error.new('MCP_PAGINATION', 'mcp: repeated cursor')
71
+ end
72
+ seen_cursors[cursor] = true
73
+ end
74
+ tools
75
+ end
76
+
77
+ def call_tool(name, arguments = {}, timeout: nil)
78
+ ensure_connected!
79
+ result = request('tools/call', { name: name, arguments: arguments }, timeout: timeout)
80
+ if result.is_a?(Hash) && result['isError']
81
+ raise Praxo::Error.new('MCP_TOOL_ERROR', "mcp: tool #{name} failed")
82
+ end
83
+ structured = result.is_a?(Hash) ? result['structuredContent'] : nil
84
+ return structured unless structured.nil?
85
+
86
+ content = result.is_a?(Hash) ? Array(result['content']) : []
87
+ texts = content.filter_map { |item| item['text'] if item['type'] == 'text' }
88
+ texts.empty? ? nil : (texts.length == 1 ? texts.first : texts)
89
+ end
90
+
91
+ def close
92
+ return if @closed
93
+
94
+ @closed = true
95
+ begin
96
+ @writer.close if @writer && !@writer.closed?
97
+ rescue IOError
98
+ nil
99
+ end
100
+ begin
101
+ @reader.close if @reader && !@reader.closed?
102
+ rescue IOError
103
+ nil
104
+ end
105
+ if @wait
106
+ begin
107
+ Process.kill('TERM', @wait.pid)
108
+ rescue Errno::ESRCH
109
+ nil
110
+ end
111
+ begin
112
+ @wait.value
113
+ rescue StandardError
114
+ nil
115
+ end
116
+ end
117
+ rescue StandardError
118
+ nil
119
+ ensure
120
+ @connected = false
121
+ end
122
+
123
+ private
124
+
125
+ def request(method, params, timeout: nil)
126
+ raise Praxo::Error.new('MCP_CLOSED', 'mcp: client is closed') if @closed
127
+
128
+ @next_id += 1
129
+ id = @next_id
130
+ write({ jsonrpc: '2.0', id: id, method: method, params: params })
131
+ deadline = Time.now + (timeout || @timeout)
132
+ loop do
133
+ remaining = deadline - Time.now
134
+ if remaining <= 0
135
+ notify('notifications/cancelled', { requestId: id, reason: 'timeout' })
136
+ raise Praxo::Error.new('MCP_TIMEOUT', "mcp: #{method} timed out")
137
+ end
138
+ readable = IO.select([@reader], nil, nil, remaining)
139
+ raise Praxo::Error.new('MCP_TIMEOUT', "mcp: #{method} timed out") unless readable
140
+
141
+ line = @reader.gets
142
+ raise Praxo::Error.new('MCP_CLOSED', 'mcp: server closed the stream') if line.nil?
143
+
144
+ begin
145
+ message = JSON.parse(line)
146
+ rescue JSON::ParserError
147
+ raise Praxo::Error.new('MCP_PROTOCOL', 'mcp: invalid JSON from server')
148
+ end
149
+ next unless message['id'] == id
150
+ if message['error']
151
+ error = message['error']
152
+ raise Praxo::Error.new('MCP_RPC', "mcp: #{error['message'] || 'rpc error'}")
153
+ end
154
+ return message['result']
155
+ end
156
+ end
157
+
158
+ def notify(method, params)
159
+ return if @closed
160
+
161
+ write({ jsonrpc: '2.0', method: method, params: params })
162
+ end
163
+
164
+ def write(message)
165
+ raise Praxo::Error.new('MCP_CLOSED', 'mcp: client is closed') if @writer.nil? || @writer.closed?
166
+
167
+ @writer.puts(JSON.generate(message))
168
+ @writer.flush
169
+ rescue IOError, Errno::EPIPE
170
+ raise Praxo::Error.new('MCP_TRANSPORT', 'mcp: write failed')
171
+ end
172
+
173
+ def ensure_connected!
174
+ start unless @connected
175
+ end
176
+ end
177
+ end
178
+ end
@@ -0,0 +1,121 @@
1
+ require 'net/http'
2
+ require 'uri'
3
+ require_relative '../models'
4
+ require_relative '../json'
5
+ require_relative '../errors'
6
+
7
+ module Praxo
8
+ module Adapters
9
+ # OpenAI-compatible chat completions adapter.
10
+ #
11
+ # transport is injectable for deterministic tests:
12
+ # ->(path, payload) { parsed_response_hash }
13
+ class OpenAICompatible
14
+ def initialize(base_url:, model:, api_key: nil, transport: nil, timeout: 60)
15
+ @base_url = base_url.to_s.sub(%r{/$}, '')
16
+ @model = model
17
+ @api_key = api_key
18
+ @transport = transport
19
+ @timeout = timeout
20
+ end
21
+
22
+ def generate(request)
23
+ payload = build_payload(request)
24
+ data = @transport ? @transport.call('/chat/completions', payload) : post('/chat/completions', payload)
25
+ parse_response(data)
26
+ end
27
+
28
+ private
29
+
30
+ def build_payload(request)
31
+ payload = {
32
+ model: @model,
33
+ messages: Array(request.messages).map { |message| message_payload(message) }
34
+ }
35
+ tools = Array(request.tools).map do |tool|
36
+ {
37
+ type: 'function',
38
+ function: {
39
+ name: tool.name,
40
+ description: tool.description,
41
+ parameters: tool.parameters || { type: 'object' }
42
+ }
43
+ }
44
+ end
45
+ payload[:tools] = tools unless tools.empty?
46
+ payload[:tool_choice] = request.tool_choice if request.tool_choice
47
+ payload[:temperature] = request.temperature if request.temperature
48
+ payload[:response_format] = request.response_format if request.response_format
49
+ payload
50
+ end
51
+
52
+ def message_payload(message)
53
+ content = message.content
54
+ if (content.nil? || content.empty?) && !Array(message.content_blocks).empty?
55
+ content = Array(message.content_blocks)
56
+ .select { |block| block.type == 'text' && block.text }
57
+ .map(&:text)
58
+ .join
59
+ end
60
+ out = { role: message.role, content: content }
61
+ if message.role == Models::ASSISTANT && !Array(message.tool_calls).empty?
62
+ out[:tool_calls] = Array(message.tool_calls).map do |call|
63
+ {
64
+ id: call.id,
65
+ type: 'function',
66
+ function: {
67
+ name: call.name,
68
+ arguments: Json.stringify(call.arguments || {})
69
+ }
70
+ }
71
+ end
72
+ end
73
+ out[:tool_call_id] = message.tool_id if message.role == Models::TOOL && message.tool_id
74
+ out
75
+ end
76
+
77
+ def parse_response(data)
78
+ choice = Array(data['choices']).first || {}
79
+ message = choice['message'] || {}
80
+ tool_calls = Array(message['tool_calls']).map do |call|
81
+ function = call['function'] || {}
82
+ arguments = function['arguments']
83
+ arguments = Json.parse(arguments) if arguments.is_a?(String) && !arguments.empty?
84
+ Models.tool_call(id: call['id'], name: function['name'], arguments: arguments || {})
85
+ end
86
+ usage = data['usage'] || {}
87
+ Models.response(
88
+ message: Models.message(
89
+ role: Models::ASSISTANT,
90
+ content: message['content'],
91
+ tool_calls: tool_calls
92
+ ),
93
+ usage: Models.usage(
94
+ input_tokens: usage['prompt_tokens'].to_i,
95
+ output_tokens: usage['completion_tokens'].to_i
96
+ ),
97
+ finish_reason: choice['finish_reason']
98
+ )
99
+ end
100
+
101
+ def post(path, payload)
102
+ uri = URI.join(@base_url + '/', path.sub(%r{^/}, ''))
103
+ request = Net::HTTP::Post.new(uri)
104
+ request['Content-Type'] = 'application/json'
105
+ request['Authorization'] = "Bearer #{@api_key}" if @api_key
106
+ request.body = Json.stringify(payload)
107
+ response = Net::HTTP.start(
108
+ uri.host,
109
+ uri.port,
110
+ use_ssl: uri.scheme == 'https',
111
+ read_timeout: @timeout
112
+ ) { |http| http.request(request) }
113
+ body = response.body.to_s
114
+ unless response.is_a?(Net::HTTPSuccess)
115
+ Praxo.error('PROVIDER_HTTP', "provider returned HTTP #{response.code}: #{body}")
116
+ end
117
+ Json.parse(body)
118
+ end
119
+ end
120
+ end
121
+ end
data/lib/praxo.rb CHANGED
@@ -8,3 +8,8 @@ require_relative 'praxo/runtime'
8
8
  require_relative 'praxo/sse'
9
9
  require_relative 'praxo/middleware'
10
10
  require_relative 'praxo/agent'
11
+ require_relative 'praxo/adapters/openai_compatible'
12
+ require_relative 'praxo/adapters/anthropic'
13
+ require_relative 'praxo/adapters/gemini'
14
+ require_relative 'praxo/adapters/mcp'
15
+ require_relative 'praxo/adapters/harmovela_sink'
data/llms.md ADDED
@@ -0,0 +1,35 @@
1
+ # PRAXO-CORE Ruby
2
+
3
+ > Embeddable, governed agent execution kernel. This file is the language-specific
4
+ > registry and coding-agent entry; it does not guarantee discovery, installation,
5
+ > or adoption.
6
+
7
+ ## Package
8
+
9
+ - package: `praxo-core`
10
+ - registry: [RubyGems](https://rubygems.org/gems/praxo-core/versions/0.4.1)
11
+ - source_version: `0.5.0`
12
+ - published_version: `0.4.1`
13
+ - install_published: `gem install praxo-core`
14
+ - install_source: `gem install praxo-core`
15
+ - source_tag: `ruby/v0.5.0`
16
+ - tier: Core
17
+ - contract: `SPEC_VERSION` `0.2.0`
18
+ - documentation: https://axisvela.github.io/praxo-core/languages/ruby/
19
+
20
+ ## Start
21
+
22
+ - README: `README.md`
23
+ - Registry introduction: `REGISTRY.md`
24
+ - Markdown entry: `llms.md`
25
+ - Compact entry: `llms.txt`
26
+ - Coding-agent contract: ../../docs/getting-started/coding-agents.md
27
+
28
+ ## Boundaries
29
+
30
+ - In-process framework; not a model provider, hosted service, workflow engine,
31
+ identity provider, or safety controller.
32
+ - No exactly-once, sandbox-isolation, production-security, real-time, or
33
+ physical-safety claim.
34
+ - Registry pages are release snapshots. Verify the published version and read the
35
+ canonical documentation for behavior and limits.
data/llms.txt ADDED
@@ -0,0 +1,35 @@
1
+ # PRAXO-CORE Ruby
2
+
3
+ > Embeddable, governed agent execution kernel. This file is the language-specific
4
+ > registry and coding-agent entry; it does not guarantee discovery, installation,
5
+ > or adoption.
6
+
7
+ # Package
8
+
9
+ - package: `praxo-core`
10
+ - registry: [RubyGems](https://rubygems.org/gems/praxo-core/versions/0.4.1)
11
+ - source_version: `0.5.0`
12
+ - published_version: `0.4.1`
13
+ - install_published: `gem install praxo-core`
14
+ - install_source: `gem install praxo-core`
15
+ - source_tag: `ruby/v0.5.0`
16
+ - tier: Core
17
+ - contract: `SPEC_VERSION` `0.2.0`
18
+ - documentation: https://axisvela.github.io/praxo-core/languages/ruby/
19
+
20
+ # Start
21
+
22
+ - README: `README.md`
23
+ - Registry introduction: `REGISTRY.md`
24
+ - Markdown entry: `llms.md`
25
+ - Compact entry: `llms.txt`
26
+ - Coding-agent contract: ../../docs/getting-started/coding-agents.md
27
+
28
+ # Boundaries
29
+
30
+ - In-process framework; not a model provider, hosted service, workflow engine,
31
+ identity provider, or safety controller.
32
+ - No exactly-once, sandbox-isolation, production-security, real-time, or
33
+ physical-safety claim.
34
+ - Registry pages are release snapshots. Verify the published version and read the
35
+ canonical documentation for behavior and limits.
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: praxo-core
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.1
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - AxisVela
@@ -19,12 +19,19 @@ extra_rdoc_files: []
19
19
  files:
20
20
  - LICENSE
21
21
  - README.md
22
+ - REGISTRY.md
22
23
  - api/0.1.0.txt
23
24
  - api/0.2.0.txt
24
25
  - api/0.3.0.txt
25
26
  - api/0.4.0.txt
26
27
  - api/0.4.1.txt
28
+ - api/0.5.0.txt
27
29
  - lib/praxo.rb
30
+ - lib/praxo/adapters/anthropic.rb
31
+ - lib/praxo/adapters/gemini.rb
32
+ - lib/praxo/adapters/harmovela_sink.rb
33
+ - lib/praxo/adapters/mcp.rb
34
+ - lib/praxo/adapters/openai_compatible.rb
28
35
  - lib/praxo/agent.rb
29
36
  - lib/praxo/errors.rb
30
37
  - lib/praxo/json.rb
@@ -35,6 +42,8 @@ files:
35
42
  - lib/praxo/runtime.rb
36
43
  - lib/praxo/sse.rb
37
44
  - lib/praxo/toolcall.rb
45
+ - llms.md
46
+ - llms.txt
38
47
  homepage: https://axisvela.github.io/praxo-core/
39
48
  licenses:
40
49
  - MIT