elelem-server 0.1.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ccf8d43f79bf8e8a3c5c138a05e9e1887d7e212a8ccdef1d498de8133a4c13ca
4
+ data.tar.gz: 5658cacb63bba0bce48f86b5ce948a1e6e18981caf7e012ddcabc6d5a1e3ec76
5
+ SHA512:
6
+ metadata.gz: 989664ee67bf8bc7d48da210b540b14e81e86aaf53a24fa300c61cc36496fade39170f4e7919d59c48bd3cbcf43b3f7cf6754d2f59117423a24a6e370fce5a81
7
+ data.tar.gz: bf048a10f1f83129bb9e8baf79f5a7cabd959d845a4a996fc34fffa18674609a57c242821b250f4bc3f610aa5abf570a08a9ea841c4239fcbd7554040c67e769
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 mo khan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: %i[spec]
data/exe/elelem-server ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "elelem/server"
5
+ require "optparse"
6
+
7
+ provider = ENV.fetch("ELELEM_PROVIDER", "stub")
8
+ port = 4567
9
+
10
+ OptionParser.new do |o|
11
+ o.banner = "Usage: elelem-server [options]"
12
+ o.on("-p", "--provider NAME", "Provider to use (default: #{provider})") { |v| provider = v }
13
+ o.on("--port PORT", Integer, "Port to listen on (default: #{port})") { |v| port = v }
14
+ o.on("-h", "--help", "Show this help") { puts o; exit }
15
+ end.parse!(ARGV)
16
+
17
+ Elelem::Server.serve(provider: provider, port: port)
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Elelem
4
+ class Server
5
+ VERSION = "0.1.0"
6
+ end
7
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Elelem
4
+ class Server
5
+ class WebTerminal
6
+ def initialize
7
+ @subscribers = []
8
+ @mutex = Mutex.new
9
+ @answers = Queue.new
10
+ end
11
+
12
+ def subscribe
13
+ Queue.new.tap { |queue| @mutex.synchronize { @subscribers << queue } }
14
+ end
15
+
16
+ def unsubscribe(queue)
17
+ @mutex.synchronize { @subscribers.delete(queue) }
18
+ end
19
+
20
+ def interactive?
21
+ true
22
+ end
23
+
24
+ def ask(prompt)
25
+ emit("prompt", prompt)
26
+ @answers.pop
27
+ end
28
+
29
+ def thinking(text)
30
+ emit("thinking", text)
31
+ end
32
+
33
+ def say(text, as: nil)
34
+ text = "\n ✗ #{text}" if as == :error
35
+ emit("content", text)
36
+ end
37
+
38
+ def doing(name, args, state: "+")
39
+ say "#{state} #{name}(#{args})"
40
+ end
41
+
42
+ def waiting
43
+ end
44
+
45
+ def print(text)
46
+ emit("content", text)
47
+ end
48
+
49
+ def display_file(path, fallback: nil)
50
+ content = File.read(path)
51
+ raise ArgumentError unless content.valid_encoding?
52
+
53
+ say(content)
54
+ rescue Errno::ENOENT, Errno::EISDIR, ArgumentError
55
+ say(fallback || path)
56
+ end
57
+
58
+ def answer(text)
59
+ @answers << text
60
+ end
61
+
62
+ def done
63
+ broadcast(type: "done")
64
+ end
65
+
66
+ private
67
+
68
+ def emit(type, text)
69
+ plain = text.to_s.gsub(/\e\[[0-9;]*[a-zA-Z]/, "")
70
+ return if plain.strip.empty?
71
+
72
+ broadcast(type: type, text: plain)
73
+ end
74
+
75
+ def broadcast(event)
76
+ @mutex.synchronize { @subscribers.each { |queue| queue << event } }
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,232 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "elelem"
4
+ require "json"
5
+ require "webrick"
6
+
7
+ require_relative "server/version"
8
+ require_relative "server/web_terminal"
9
+
10
+ module Elelem
11
+ class Server
12
+ def self.serve(provider: "stub", port: 4567, toolbox: Toolbox.new)
13
+ llm_provider = Config.build_provider(provider)
14
+ web_terminal = WebTerminal.new
15
+ agent = Agent.new(llm_provider, toolbox: toolbox, output: web_terminal, input: web_terminal)
16
+ Config.apply(agent)
17
+ new(agent, port: port).start
18
+ end
19
+
20
+ def initialize(agent, port: 4567, address: "0.0.0.0")
21
+ @agent = agent
22
+ @port = port
23
+ @address = address
24
+ @terminal = agent.output
25
+ end
26
+
27
+ def start
28
+ server = WEBrick::HTTPServer.new(
29
+ Port: @port,
30
+ BindAddress: @address,
31
+ Logger: WEBrick::Log.new(File::NULL),
32
+ AccessLog: []
33
+ )
34
+ server.mount_proc("/", &method(:index))
35
+ server.mount_proc("/events", &method(:events))
36
+ server.mount_proc("/message", &method(:message))
37
+ server.mount_proc("/answer", &method(:answer))
38
+
39
+ trap("INT") { server.shutdown }
40
+ $stdout.puts "elelem v#{VERSION} listening on http://#{@address}:#{@port}"
41
+ server.start
42
+ end
43
+
44
+ private
45
+
46
+ def index(_req, res)
47
+ res.content_type = "text/html; charset=utf-8"
48
+ res.body = INDEX
49
+ end
50
+
51
+ def events(_req, res)
52
+ res.content_type = "text/event-stream"
53
+ res["Cache-Control"] = "no-cache"
54
+ res.chunked = true
55
+ res.body = ->(out) { stream(out) }
56
+ end
57
+
58
+ def stream(out)
59
+ events = @terminal.subscribe
60
+ loop do
61
+ out.write("data: #{JSON.dump(events.pop)}\n\n")
62
+ end
63
+ rescue IOError, Errno::EPIPE, Errno::ECONNRESET
64
+ nil
65
+ ensure
66
+ @terminal.unsubscribe(events)
67
+ end
68
+
69
+ def message(req, res)
70
+ text = JSON.parse(req.body)["text"].to_s
71
+ Thread.new do
72
+ @agent.turn(text)
73
+ rescue => e
74
+ @terminal.say("Error: #{e.message}")
75
+ ensure
76
+ @terminal.done
77
+ end
78
+ res.status = 204
79
+ end
80
+
81
+ def answer(req, res)
82
+ @terminal.answer(JSON.parse(req.body)["text"].to_s)
83
+ res.status = 204
84
+ end
85
+
86
+ INDEX = <<~HTML
87
+ <!doctype html>
88
+ <html lang="en">
89
+ <head>
90
+ <meta charset="utf-8">
91
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
92
+ <title>elelem</title>
93
+ <style>
94
+ :root { color-scheme: dark; }
95
+ * { box-sizing: border-box; }
96
+ body {
97
+ margin: 0; height: 100dvh; display: flex; flex-direction: column;
98
+ background: #16161a; color: #e6e6e6;
99
+ font: 16px/1.55 ui-sans-serif, system-ui, -apple-system, sans-serif;
100
+ }
101
+ #log { flex: 1; overflow-y: auto; padding: 1rem; -webkit-overflow-scrolling: touch; }
102
+ .msg { max-width: 46rem; margin: 0 auto 1rem; padding: .65rem .85rem; border-radius: .6rem; }
103
+ .user { background: #2d3a4f; }
104
+ .assistant { background: #22222a; }
105
+ .thinking { opacity: .55; font-style: italic; white-space: pre-wrap; }
106
+ .msg pre {
107
+ background: #0d0d10; padding: .7rem; border-radius: .4rem;
108
+ overflow-x: auto; font-size: .875rem;
109
+ }
110
+ .msg code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
111
+ .prompt { max-width: 46rem; margin: 0 auto 1rem; padding: .85rem; border-radius: .6rem; background: #4a3a1e; }
112
+ .prompt button {
113
+ font-size: 1rem; padding: .7rem 1.4rem; margin: .5rem .5rem 0 0;
114
+ border: 0; border-radius: .5rem; color: #fff; touch-action: manipulation;
115
+ }
116
+ .allow { background: #2f7d4f; }
117
+ .deny { background: #8c3535; }
118
+ form { display: flex; gap: .5rem; padding: .75rem; padding-bottom: max(.75rem, env(safe-area-inset-bottom));
119
+ border-top: 1px solid #2c2c33; background: #1b1b20; }
120
+ textarea {
121
+ flex: 1; resize: none; font: inherit; padding: .6rem; border-radius: .5rem;
122
+ border: 1px solid #35353d; background: #101014; color: inherit;
123
+ }
124
+ button.send { font-size: 1rem; padding: .6rem 1.2rem; border: 0; border-radius: .5rem; background: #3b6ea5; color: #fff; }
125
+ </style>
126
+ </head>
127
+ <body>
128
+ <div id="log"></div>
129
+ <form id="composer">
130
+ <textarea id="input" rows="1" placeholder="Message elelem…" autocapitalize="sentences"></textarea>
131
+ <button class="send" type="submit">Send</button>
132
+ </form>
133
+ <script>
134
+ const log = document.getElementById("log");
135
+ const input = document.getElementById("input");
136
+ let current = null;
137
+
138
+ const atBottom = () => log.scrollHeight - log.scrollTop - log.clientHeight < 80;
139
+ const scroll = (was) => { if (was) log.scrollTop = log.scrollHeight; };
140
+
141
+ function escape(text) {
142
+ return text.replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[c]);
143
+ }
144
+
145
+ function render(text) {
146
+ return escape(text)
147
+ .replace(/```(\\w*)\\n([\\s\\S]*?)```/g, (_m, _lang, code) => "<pre><code>" + code + "</code></pre>")
148
+ .replace(/`([^`\\n]+)`/g, "<code>$1</code>")
149
+ .replace(/\\*\\*([^*]+)\\*\\*/g, "<strong>$1</strong>")
150
+ .replace(/\\n/g, "<br>");
151
+ }
152
+
153
+ function bubble(cls) {
154
+ const was = atBottom();
155
+ const el = document.createElement("div");
156
+ el.className = "msg " + cls;
157
+ log.appendChild(el);
158
+ scroll(was);
159
+ return el;
160
+ }
161
+
162
+ function append(cls, text) {
163
+ if (!current || current.dataset.cls !== cls) {
164
+ current = bubble(cls);
165
+ current.dataset.cls = cls;
166
+ current.dataset.raw = "";
167
+ }
168
+ const was = atBottom();
169
+ current.dataset.raw += text;
170
+ current.innerHTML = render(current.dataset.raw);
171
+ scroll(was);
172
+ }
173
+
174
+ function askPermission(text) {
175
+ current = null;
176
+ const was = atBottom();
177
+ const el = document.createElement("div");
178
+ el.className = "prompt";
179
+ el.innerHTML = "<div>" + escape(text) + "</div>";
180
+ const respond = (answer) => {
181
+ el.querySelectorAll("button").forEach((b) => b.remove());
182
+ el.insertAdjacentHTML("beforeend", "<div><em>" + answer + "</em></div>");
183
+ fetch("/answer", { method: "POST", body: JSON.stringify({ text: answer }) });
184
+ };
185
+ const allow = document.createElement("button");
186
+ allow.className = "allow";
187
+ allow.textContent = "Allow";
188
+ allow.onclick = () => respond("y");
189
+ const deny = document.createElement("button");
190
+ deny.className = "deny";
191
+ deny.textContent = "Deny";
192
+ deny.onclick = () => respond("n");
193
+ el.append(allow, deny);
194
+ log.appendChild(el);
195
+ scroll(was);
196
+ }
197
+
198
+ new EventSource("/events").onmessage = (e) => {
199
+ const event = JSON.parse(e.data);
200
+ if (event.type === "content") append("assistant", event.text);
201
+ else if (event.type === "thinking") append("thinking", event.text);
202
+ else if (event.type === "prompt") askPermission(event.text);
203
+ else if (event.type === "done") current = null;
204
+ };
205
+
206
+ document.getElementById("composer").onsubmit = (e) => {
207
+ e.preventDefault();
208
+ const text = input.value.trim();
209
+ if (!text) return;
210
+ append("user", text);
211
+ current = null;
212
+ input.value = "";
213
+ fetch("/message", { method: "POST", body: JSON.stringify({ text: text }) });
214
+ };
215
+
216
+ input.addEventListener("keydown", (e) => {
217
+ if (e.key === "Enter" && !e.shiftKey) {
218
+ e.preventDefault();
219
+ document.getElementById("composer").requestSubmit();
220
+ }
221
+ });
222
+
223
+ input.addEventListener("input", () => {
224
+ input.style.height = "auto";
225
+ input.style.height = Math.min(input.scrollHeight, 160) + "px";
226
+ });
227
+ </script>
228
+ </body>
229
+ </html>
230
+ HTML
231
+ end
232
+ end
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ RSpec.describe Elelem::Server::WebTerminal do
4
+ subject { described_class.new }
5
+
6
+ let(:events) { subject.subscribe }
7
+
8
+ before { events }
9
+
10
+ def drain(queue = events)
11
+ [].tap { |collected| collected << queue.pop until queue.empty? }
12
+ end
13
+
14
+ describe "#interactive?" do
15
+ it { expect(subject).to be_interactive }
16
+ end
17
+
18
+ describe "#say" do
19
+ it "emits content" do
20
+ subject.say("hello")
21
+ expect(drain).to eq([{ type: "content", text: "hello" }])
22
+ end
23
+
24
+ it "ignores blank text" do
25
+ subject.say(" ")
26
+ subject.say(nil)
27
+ expect(drain).to be_empty
28
+ end
29
+
30
+ it "strips ANSI colour codes meant for a terminal" do
31
+ subject.say("+ \e[36mexecute\e[0m(...)")
32
+ expect(drain).to eq([{ type: "content", text: "+ execute(...)" }])
33
+ end
34
+
35
+ it "accepts the as: keyword like Terminal#say" do
36
+ subject.say("hello", as: :markdown)
37
+ expect(drain).to eq([{ type: "content", text: "hello" }])
38
+ end
39
+ end
40
+
41
+ describe "#thinking" do
42
+ it "emits a thinking event" do
43
+ subject.thinking("pondering")
44
+ expect(drain).to eq([{ type: "thinking", text: "pondering" }])
45
+ end
46
+ end
47
+
48
+ describe "#display_file" do
49
+ it "emits the file's contents" do
50
+ Tempfile.create do |file|
51
+ file.write("contents")
52
+ file.flush
53
+ subject.display_file(file.path, fallback: "fallback")
54
+ expect(drain).to eq([{ type: "content", text: "contents" }])
55
+ end
56
+ end
57
+
58
+ it "emits the fallback when the file is missing" do
59
+ subject.display_file("/no/such/file.rb", fallback: "contents")
60
+ expect(drain).to eq([{ type: "content", text: "contents" }])
61
+ end
62
+
63
+ it "emits the fallback when the file is not valid UTF-8" do
64
+ Tempfile.create do |file|
65
+ file.binmode
66
+ file.write("\xFF\xFE\x00\x01")
67
+ file.flush
68
+ subject.display_file(file.path, fallback: "contents")
69
+ expect(drain).to eq([{ type: "content", text: "contents" }])
70
+ end
71
+ end
72
+ end
73
+
74
+ describe "#done" do
75
+ it "emits a turn boundary" do
76
+ subject.done
77
+ expect(drain).to eq([{ type: "done" }])
78
+ end
79
+ end
80
+
81
+ describe "#waiting" do
82
+ it "is a no-op" do
83
+ subject.waiting
84
+ expect(drain).to be_empty
85
+ end
86
+ end
87
+
88
+ describe "multiple subscribers" do
89
+ it "every subscriber receives every event" do
90
+ other = subject.subscribe
91
+ subject.say("broadcast")
92
+ expect(drain).to eq([{ type: "content", text: "broadcast" }])
93
+ expect(drain(other)).to eq([{ type: "content", text: "broadcast" }])
94
+ end
95
+
96
+ it "stops delivering after unsubscribe" do
97
+ subject.unsubscribe(events)
98
+ subject.say("gone")
99
+ expect(drain).to be_empty
100
+ end
101
+ end
102
+
103
+ describe "#ask" do
104
+ it "emits a prompt and blocks until answered" do
105
+ thread = Thread.new { subject.ask("Allow?") }
106
+ expect(events.pop).to eq({ type: "prompt", text: "Allow?" })
107
+ subject.answer("n")
108
+ expect(thread.value).to eq("n")
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "tempfile"
4
+ require_relative "../lib/elelem/server"
5
+
6
+ RSpec.configure do |config|
7
+ config.disable_monkey_patching!
8
+
9
+ config.expect_with :rspec do |c|
10
+ c.syntax = :expect
11
+ end
12
+ end
metadata ADDED
@@ -0,0 +1,95 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: elelem-server
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - mo khan
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: elelem
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '0.11'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '0.11'
26
+ - !ruby/object:Gem::Dependency
27
+ name: json
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '3.0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '3.0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: webrick
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '1.9'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '1.9'
54
+ description: A web UI server plugin for elelem.
55
+ email:
56
+ - mo@mokhan.ca
57
+ executables:
58
+ - elelem-server
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".rspec"
63
+ - LICENSE.txt
64
+ - Rakefile
65
+ - exe/elelem-server
66
+ - lib/elelem/server.rb
67
+ - lib/elelem/server/version.rb
68
+ - lib/elelem/server/web_terminal.rb
69
+ - spec/elelem/server/web_terminal_spec.rb
70
+ - spec/spec_helper.rb
71
+ homepage: https://src.mokhan.ca/elelem/server
72
+ licenses:
73
+ - MIT
74
+ metadata:
75
+ allowed_push_host: https://rubygems.org
76
+ homepage_uri: https://src.mokhan.ca/elelem/server
77
+ source_code_uri: https://src.mokhan.ca/elelem/server
78
+ rdoc_options: []
79
+ require_paths:
80
+ - lib
81
+ required_ruby_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: 4.0.0
86
+ required_rubygems_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ requirements: []
92
+ rubygems_version: 4.0.20
93
+ specification_version: 4
94
+ summary: A web UI server plugin for elelem.
95
+ test_files: []