elelem-daemon 0.1.0 → 0.2.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 +4 -4
- data/LICENSE.txt +1 -1
- data/exe/elelemd +22 -4
- data/lib/elelem/daemon/client.rb +66 -21
- data/lib/elelem/daemon/clients.rb +32 -0
- data/lib/elelem/daemon/connection.rb +8 -0
- data/lib/elelem/daemon/terminal.rb +17 -4
- data/lib/elelem/daemon/version.rb +1 -1
- data/lib/elelem/daemon/worker.rb +182 -35
- data/lib/elelem/daemon.rb +33 -10
- metadata +2 -16
- data/.agents/backlog/001-named-sessions.md +0 -19
- data/.agents/backlog/002-agent-to-agent.md +0 -23
- data/.github/workflows/release.yml +0 -63
- data/.release-please-manifest.json +0 -3
- data/.rspec +0 -1
- data/.rubocop.yml +0 -62
- data/CHANGELOG.md +0 -10
- data/README.md +0 -106
- data/Rakefile +0 -8
- data/release-please-config.json +0 -12
- data/spec/elelem/daemon/client_spec.rb +0 -88
- data/spec/elelem/daemon/connection_spec.rb +0 -40
- data/spec/elelem/daemon/terminal_spec.rb +0 -44
- data/spec/elelem/daemon_spec.rb +0 -253
- data/spec/spec_helper.rb +0 -12
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: bc0749ca92402f8afea70fe2ce28513f722d7de16e756c832430ec4a52be423e
|
|
4
|
+
data.tar.gz: fc359130e2d13d38d7eb51a21905c409964f4cf44be443f80ea31bf29dab2016
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: c621a183068f959fca0106080a5d530eaa327b662f5753343f7e1434ce8b76dff6c5b60ba30cf1453cba5a3d341a17dd7cd00af8c9a545a668a386d5757cd4cf
|
|
7
|
+
data.tar.gz: '0667039d89181c9fd8f63657bcd346bf86539e6ceba12112812d14152b8f19d5bbd83ac17182f6b64b39a2fa54bc976be2877f920ebdada7810f7c3fb508ad27'
|
data/LICENSE.txt
CHANGED
data/exe/elelemd
CHANGED
|
@@ -6,6 +6,9 @@ require "optparse"
|
|
|
6
6
|
|
|
7
7
|
options = {}
|
|
8
8
|
max_workers = Elelem::Daemon::MAX_WORKERS
|
|
9
|
+
idle = Elelem::Daemon::Worker::IDLE
|
|
10
|
+
session = nil
|
|
11
|
+
detach = false
|
|
9
12
|
socket = Elelem::Daemon.socket_path
|
|
10
13
|
|
|
11
14
|
parser = OptionParser.new do |o|
|
|
@@ -16,13 +19,20 @@ parser = OptionParser.new do |o|
|
|
|
16
19
|
serve Run the daemon (default)
|
|
17
20
|
ask <prompt> Send one prompt for this folder; reads stdin if piped
|
|
18
21
|
chat Talk to the daemon from this folder
|
|
22
|
+
attach <name> Talk in a named session that is running
|
|
23
|
+
ls List the named sessions
|
|
19
24
|
|
|
20
25
|
Options:
|
|
21
26
|
TEXT
|
|
22
27
|
o.on("-s", "--socket PATH", "Socket (default: #{socket})") { |v| socket = v }
|
|
23
28
|
o.on("-p", "--provider NAME", "Provider to use") { |v| options[:provider] = v }
|
|
24
29
|
o.on("--model NAME", "Model to use, passed to the provider") { |v| options[:model] = v }
|
|
30
|
+
o.on("-S", "--session NAME", "Use the named session, starting it here if it is not running") { |v| session = v }
|
|
31
|
+
o.on("-d", "--detach", "With ask: return once the prompt is queued") { detach = true }
|
|
25
32
|
o.on("--max-workers N", Integer, "Connections served at once (default: #{max_workers})") { |v| max_workers = v }
|
|
33
|
+
o.on("--idle SECONDS", Integer, "End a session idle this long with nobody attached (default: #{idle})") do |v|
|
|
34
|
+
idle = v
|
|
35
|
+
end
|
|
26
36
|
o.on("-h", "--help", "Show this help") do
|
|
27
37
|
puts o
|
|
28
38
|
exit
|
|
@@ -34,7 +44,7 @@ begin
|
|
|
34
44
|
case args.shift || "serve"
|
|
35
45
|
when "serve"
|
|
36
46
|
provider = options.fetch(:provider) { ENV.fetch("ELELEM_PROVIDER", "demo") }
|
|
37
|
-
Elelem::Daemon.new(path: socket, provider: provider, max_workers: max_workers).start
|
|
47
|
+
Elelem::Daemon.new(path: socket, provider: provider, max_workers: max_workers, idle: idle).start
|
|
38
48
|
when "ask"
|
|
39
49
|
abort "Usage: elelemd ask <prompt>" if args.empty?
|
|
40
50
|
prompt = args.join(" ")
|
|
@@ -42,10 +52,18 @@ begin
|
|
|
42
52
|
piped = !$stdout.tty?
|
|
43
53
|
output = piped ? Elelem::Output.new(stream: $stderr) : Elelem::Terminal.new
|
|
44
54
|
input = $stdin.tty? ? Elelem::Input.new : Elelem::NullInput.new
|
|
45
|
-
|
|
46
|
-
|
|
55
|
+
client = Elelem::Daemon::Client.new(path: socket, input: input, output: output, session: session)
|
|
56
|
+
reply = client.ask(prompt, detach: detach, **options)
|
|
57
|
+
puts reply if piped && !detach
|
|
47
58
|
when "chat"
|
|
48
|
-
Elelem::Daemon::Client.new(path: socket).chat(**options)
|
|
59
|
+
Elelem::Daemon::Client.new(path: socket, session: session).chat(**options)
|
|
60
|
+
when "attach"
|
|
61
|
+
abort "Usage: elelemd attach <name>" unless (name = args.shift)
|
|
62
|
+
Elelem::Daemon::Client.new(path: socket, session: name).attach
|
|
63
|
+
when "ls"
|
|
64
|
+
Elelem::Daemon.sessions(Elelem::Daemon.sessions_dir(socket)).each do |s|
|
|
65
|
+
puts format("%-16s %-4s %2d attached %s", s["name"], s["busy"] ? "busy" : "idle", s["clients"], s["cwd"])
|
|
66
|
+
end
|
|
49
67
|
else
|
|
50
68
|
abort parser.help
|
|
51
69
|
end
|
data/lib/elelem/daemon/client.rb
CHANGED
|
@@ -4,24 +4,31 @@ module Elelem
|
|
|
4
4
|
class Daemon
|
|
5
5
|
# Talks to elelemd: sends prompts for the current folder, draws the
|
|
6
6
|
# events, and answers approval prompts when a person is there to.
|
|
7
|
+
#
|
|
8
|
+
# With a session name it attaches to that session's socket, or, if the
|
|
9
|
+
# session is not running, asks elelemd to start it in this folder.
|
|
7
10
|
class Client
|
|
8
|
-
def initialize(path: Daemon.socket_path, input: Input.new, output: Terminal.new)
|
|
11
|
+
def initialize(path: Daemon.socket_path, input: Input.new, output: Elelem::Terminal.new, session: nil)
|
|
9
12
|
@path = path
|
|
10
13
|
@input = input
|
|
11
14
|
@output = output
|
|
15
|
+
@session = session
|
|
12
16
|
end
|
|
13
17
|
|
|
14
|
-
# One prompt; returns the reply.
|
|
15
|
-
|
|
18
|
+
# One prompt; returns the reply. With detach, returns once the prompt
|
|
19
|
+
# is queued, and the turn runs on in the session.
|
|
20
|
+
def ask(prompt, detach: false, **)
|
|
16
21
|
connect(prompt: prompt, **)
|
|
17
|
-
wait
|
|
22
|
+
wait(detach: detach)
|
|
18
23
|
ensure
|
|
19
24
|
@socket&.close
|
|
20
25
|
end
|
|
21
26
|
|
|
22
|
-
# A conversation: one prompt per line until end of input.
|
|
23
|
-
|
|
24
|
-
|
|
27
|
+
# A conversation: one prompt per line until end of input. Attaching to
|
|
28
|
+
# a session that is running a turn shows that turn first.
|
|
29
|
+
def chat(create: true, **)
|
|
30
|
+
connect(create: create, **)
|
|
31
|
+
watch if @hello["turn"]
|
|
25
32
|
while (line = @input.ask("> "))
|
|
26
33
|
next if line.empty?
|
|
27
34
|
|
|
@@ -33,30 +40,60 @@ module Elelem
|
|
|
33
40
|
@socket&.close
|
|
34
41
|
end
|
|
35
42
|
|
|
43
|
+
# Chat in a session that is already running.
|
|
44
|
+
def attach(**) = chat(create: false, **)
|
|
45
|
+
|
|
36
46
|
private
|
|
37
47
|
|
|
38
|
-
def
|
|
39
|
-
@
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
48
|
+
def watch
|
|
49
|
+
@output.say("» #{@hello["prompt"]}")
|
|
50
|
+
wait(@hello["turn"])
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def connect(prompt: nil, create: true, **)
|
|
54
|
+
if @session && (socket = dial(File.join(Daemon.sessions_dir(@path), "#{@session}.sock")))
|
|
55
|
+
start(socket)
|
|
56
|
+
@connection.write(prompt: prompt) if prompt
|
|
57
|
+
else
|
|
58
|
+
raise "no session named #{@session}" if @session && !create
|
|
59
|
+
|
|
60
|
+
start(dial(@path) || raise("elelemd is not running (no socket at #{@path})"))
|
|
61
|
+
@connection.write(request(prompt: prompt, **))
|
|
62
|
+
end
|
|
63
|
+
end
|
|
43
64
|
|
|
44
|
-
|
|
65
|
+
def dial(path)
|
|
66
|
+
UNIXSocket.new(path)
|
|
45
67
|
rescue Errno::ENOENT, Errno::ECONNREFUSED
|
|
46
|
-
|
|
68
|
+
nil
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def start(socket)
|
|
72
|
+
@socket = socket
|
|
73
|
+
@connection = Connection.new(@socket, on_hang_up: -> { raise "elelemd closed the connection" })
|
|
74
|
+
@hello = @connection.read || {}
|
|
75
|
+
protocol = @hello["protocol"]
|
|
76
|
+
raise "elelemd speaks protocol #{protocol.inspect}, not #{PROTOCOL}" unless protocol == PROTOCOL
|
|
47
77
|
end
|
|
48
78
|
|
|
49
79
|
def request(provider: nil, model: nil, **rest)
|
|
50
|
-
{ cwd: Dir.pwd, env: ENV.to_h, interactive: @input.interactive?, provider:, model:,
|
|
80
|
+
{ cwd: Dir.pwd, env: ENV.to_h, interactive: @input.interactive?, session: @session, provider:, model:,
|
|
81
|
+
**rest }.compact
|
|
51
82
|
end
|
|
52
83
|
|
|
53
|
-
# Draws events until the turn is done
|
|
54
|
-
|
|
84
|
+
# Draws events until the turn is done: the given one, or else the next
|
|
85
|
+
# one this client queues. Ctrl-C asks elelemd to stop it.
|
|
86
|
+
def wait(turn = nil, detach: false)
|
|
55
87
|
loop do
|
|
56
88
|
event = @connection.read or raise(@error || "elelemd closed the connection")
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
89
|
+
case event["type"]
|
|
90
|
+
when "queued"
|
|
91
|
+
turn ||= event["turn"]
|
|
92
|
+
return if detach
|
|
93
|
+
when "done" then return event["reply"] if event["turn"] == turn
|
|
94
|
+
when "turn" then @output.say("» #{event["prompt"]}") unless event["turn"] == turn
|
|
95
|
+
else draw(event)
|
|
96
|
+
end
|
|
60
97
|
rescue Interrupt
|
|
61
98
|
@connection.write(interrupt: true)
|
|
62
99
|
end
|
|
@@ -67,10 +104,18 @@ module Elelem
|
|
|
67
104
|
when "content" then @output.say(event["text"], as: event["as"]&.to_sym)
|
|
68
105
|
when "thinking" then @output.thinking(event["text"])
|
|
69
106
|
when "tool" then @output.doing(event["name"], event["args"], state: event["state"] || "+")
|
|
70
|
-
when "prompt" then
|
|
107
|
+
when "prompt" then answer(event)
|
|
71
108
|
when "error" then @output.say(@error = event["text"], as: :error)
|
|
72
109
|
end
|
|
73
110
|
end
|
|
111
|
+
|
|
112
|
+
# In a session the prompt stays open for another client, so one that
|
|
113
|
+
# cannot answer leaves it be.
|
|
114
|
+
def answer(event)
|
|
115
|
+
return unless @input.interactive?
|
|
116
|
+
|
|
117
|
+
@connection.write(id: event["id"], answer: @input.ask(event["text"]))
|
|
118
|
+
end
|
|
74
119
|
end
|
|
75
120
|
end
|
|
76
121
|
end
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Elelem
|
|
4
|
+
class Daemon
|
|
5
|
+
# The connections attached to a worker, written to as one. A connection
|
|
6
|
+
# that hangs up is dropped by its own callback.
|
|
7
|
+
class Clients
|
|
8
|
+
def initialize(on_change: ->(_size) {})
|
|
9
|
+
@connections = []
|
|
10
|
+
@on_change = on_change
|
|
11
|
+
@lock = Mutex.new
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
def add(connection)
|
|
15
|
+
@lock.synchronize { @connections << connection }
|
|
16
|
+
@on_change.call(size)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def remove(connection)
|
|
20
|
+
removed = @lock.synchronize { @connections.delete(connection) }
|
|
21
|
+
@on_change.call(size) if removed
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def write(event)
|
|
25
|
+
@lock.synchronize { @connections.dup }.each { it.write(event) }
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def size = @lock.synchronize { @connections.size }
|
|
29
|
+
def empty? = size.zero?
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
@@ -22,6 +22,8 @@ module Elelem
|
|
|
22
22
|
JSON.parse(line).tap { |message| raise ArgumentError, "expected a JSON object" unless message.is_a?(Hash) }
|
|
23
23
|
rescue JSON::ParserError
|
|
24
24
|
raise ArgumentError, "expected a JSON object"
|
|
25
|
+
rescue *HUNG_UP
|
|
26
|
+
nil
|
|
25
27
|
end
|
|
26
28
|
|
|
27
29
|
def write(event)
|
|
@@ -29,6 +31,12 @@ module Elelem
|
|
|
29
31
|
rescue *HUNG_UP
|
|
30
32
|
@on_hang_up.call
|
|
31
33
|
end
|
|
34
|
+
|
|
35
|
+
def close
|
|
36
|
+
@socket.close
|
|
37
|
+
rescue IOError
|
|
38
|
+
nil
|
|
39
|
+
end
|
|
32
40
|
end
|
|
33
41
|
end
|
|
34
42
|
end
|
|
@@ -6,7 +6,8 @@ module Elelem
|
|
|
6
6
|
#
|
|
7
7
|
# It always reports itself interactive, so a tool that needs approval
|
|
8
8
|
# asks instead of being approved unseen. A client that cannot answer,
|
|
9
|
-
# such as a script, gets no prompt: the request is denied.
|
|
9
|
+
# such as a script, gets no prompt: the request is denied. A named
|
|
10
|
+
# session always asks, and the prompt stays open until a client answers.
|
|
10
11
|
class Terminal
|
|
11
12
|
ANSI = /\e\[[0-9;]*[a-zA-Z]/
|
|
12
13
|
|
|
@@ -24,17 +25,29 @@ module Elelem
|
|
|
24
25
|
return unless @interactive
|
|
25
26
|
|
|
26
27
|
queue = Queue.new
|
|
27
|
-
|
|
28
|
-
@
|
|
28
|
+
event = { type: "prompt", text: plain(prompt) }
|
|
29
|
+
id = @lock.synchronize { (@next_id += 1).tap { @prompts[it] = [queue, event.merge(id: it)] } }
|
|
30
|
+
@connection.write(event.merge(id: id))
|
|
29
31
|
queue.pop
|
|
30
32
|
ensure
|
|
31
33
|
@lock.synchronize { @prompts.delete(id) } if id
|
|
32
34
|
end
|
|
33
35
|
|
|
36
|
+
# Only the first answer counts. Every client hears that it came, before
|
|
37
|
+
# the turn goes on.
|
|
34
38
|
def answer(id, text)
|
|
35
|
-
@lock.synchronize { @prompts
|
|
39
|
+
queue, = @lock.synchronize { @prompts.delete(id) }
|
|
40
|
+
return unless queue
|
|
41
|
+
|
|
42
|
+
@connection.write(type: "answered", id: id)
|
|
43
|
+
queue.push(text)
|
|
36
44
|
end
|
|
37
45
|
|
|
46
|
+
# The prompts nobody has answered yet, for a client that attaches.
|
|
47
|
+
def open_prompts = @lock.synchronize { @prompts.values.map(&:last) }
|
|
48
|
+
|
|
49
|
+
def asking? = @lock.synchronize { @prompts.any? }
|
|
50
|
+
|
|
38
51
|
def say(text, as: nil)
|
|
39
52
|
emit("content", text, as: as&.to_s)
|
|
40
53
|
end
|
data/lib/elelem/daemon/worker.rb
CHANGED
|
@@ -2,18 +2,32 @@
|
|
|
2
2
|
|
|
3
3
|
module Elelem
|
|
4
4
|
class Daemon
|
|
5
|
-
# Serves
|
|
6
|
-
# group. Turns run on the main thread, one at a time; a reader thread
|
|
7
|
-
# queues prompts and passes on answers. An interrupt signals the
|
|
8
|
-
# group, so it stops a running command as Ctrl-C does in a terminal.
|
|
5
|
+
# Serves a conversation in a forked process that leads its own process
|
|
6
|
+
# group. Turns run on the main thread, one at a time; a reader thread per
|
|
7
|
+
# client queues prompts and passes on answers. An interrupt signals the
|
|
8
|
+
# whole group, so it stops a running command as Ctrl-C does in a terminal.
|
|
9
|
+
#
|
|
10
|
+
# A plain worker ends with its connection. A named session also listens
|
|
11
|
+
# on its own socket, sends every event to every client attached, and
|
|
12
|
+
# ends only after it has been idle with nobody attached.
|
|
9
13
|
class Worker
|
|
10
14
|
TTY_ONLY = %w[shell].freeze
|
|
15
|
+
IDLE = 3600
|
|
16
|
+
NAME = /\A[A-Za-z0-9][\w.-]{0,63}\z/
|
|
11
17
|
|
|
12
|
-
def initialize(socket, provider:, status:)
|
|
13
|
-
@
|
|
18
|
+
def initialize(socket, provider:, status:, sessions: nil, idle: IDLE)
|
|
19
|
+
@first = Connection.new(socket, on_hang_up: -> { detach(@first) })
|
|
14
20
|
@provider = provider
|
|
15
21
|
@status = status
|
|
22
|
+
@sessions = sessions
|
|
23
|
+
@idle = idle
|
|
16
24
|
@prompts = Queue.new
|
|
25
|
+
@lock = Monitor.new
|
|
26
|
+
@queued = 0
|
|
27
|
+
@finished = 0
|
|
28
|
+
@pending = {}
|
|
29
|
+
@leaving = []
|
|
30
|
+
@clients = Clients.new(on_change: method(:clients_changed))
|
|
17
31
|
end
|
|
18
32
|
|
|
19
33
|
# Never returns: a worker must not run the daemon's own cleanup.
|
|
@@ -23,10 +37,11 @@ module Elelem
|
|
|
23
37
|
$stdin.reopen(File::NULL)
|
|
24
38
|
serve
|
|
25
39
|
rescue StandardError, ScriptError => e
|
|
26
|
-
@
|
|
40
|
+
@clients.write(type: "error", text: e.message)
|
|
27
41
|
rescue SystemExit, SignalException
|
|
28
42
|
nil
|
|
29
43
|
ensure
|
|
44
|
+
close_session
|
|
30
45
|
$stdout.flush
|
|
31
46
|
$stderr.flush
|
|
32
47
|
exit!(0)
|
|
@@ -35,13 +50,15 @@ module Elelem
|
|
|
35
50
|
private
|
|
36
51
|
|
|
37
52
|
def serve
|
|
38
|
-
@
|
|
39
|
-
|
|
40
|
-
|
|
53
|
+
@clients.add(@first)
|
|
54
|
+
@first.write(type: "hello", protocol: PROTOCOL)
|
|
55
|
+
request = @first.read or return
|
|
56
|
+
return @first.write(@status) if request["status"]
|
|
41
57
|
|
|
42
58
|
open_session(request)
|
|
43
|
-
|
|
44
|
-
|
|
59
|
+
host(request["session"]) if request.key?("session")
|
|
60
|
+
queue(request["prompt"].to_s, @first) if request.key?("prompt")
|
|
61
|
+
Thread.new { read_messages(@first) }
|
|
45
62
|
turns
|
|
46
63
|
end
|
|
47
64
|
|
|
@@ -49,10 +66,11 @@ module Elelem
|
|
|
49
66
|
cwd = folder(request["cwd"])
|
|
50
67
|
ENV.update(request["env"].to_h { |name, value| [name.to_s, value&.to_s] }) if request["env"].is_a?(Hash)
|
|
51
68
|
Dir.chdir(cwd)
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
@
|
|
55
|
-
|
|
69
|
+
interactive = request.key?("session") || request["interactive"] == true
|
|
70
|
+
@terminal = Terminal.new(@clients, interactive: interactive)
|
|
71
|
+
@info = { provider: request["provider"] || @provider, model: request["model"] }
|
|
72
|
+
@session = Config.build_session(@info[:provider], input: @terminal, output: @terminal,
|
|
73
|
+
provider_options: { model: request["model"] }.compact)
|
|
56
74
|
end
|
|
57
75
|
|
|
58
76
|
def folder(cwd)
|
|
@@ -61,52 +79,148 @@ module Elelem
|
|
|
61
79
|
raise ArgumentError, "cwd must be the absolute path of a folder"
|
|
62
80
|
end
|
|
63
81
|
|
|
82
|
+
# Takes the name's lock, so one process at a time serves it, and listens
|
|
83
|
+
# on the session's own socket.
|
|
84
|
+
def host(name)
|
|
85
|
+
unless name.is_a?(String) && name.match?(NAME)
|
|
86
|
+
raise ArgumentError, "a session name is letters, digits, _, . and -"
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
FileUtils.mkdir_p(@sessions, mode: 0o700)
|
|
90
|
+
@hold = File.open(File.join(@sessions, "#{name}.lock"), File::RDWR | File::CREAT, 0o600)
|
|
91
|
+
raise "session #{name} is already running; attach to it" unless @hold.flock(File::LOCK_EX | File::LOCK_NB)
|
|
92
|
+
|
|
93
|
+
@name = name
|
|
94
|
+
@started = Time.now.utc.strftime("%FT%TZ")
|
|
95
|
+
FileUtils.rm_f(path("sock")) # left by a session that died; the lock says none is running
|
|
96
|
+
@server = Daemon.private_umask { UNIXServer.new(path("sock")) }
|
|
97
|
+
@first.write(type: "session", name: name, socket: path("sock"))
|
|
98
|
+
write_sidecar
|
|
99
|
+
Thread.new { accept }
|
|
100
|
+
Thread.new { watch }
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def path(extension) = File.join(@sessions, "#{@name}.#{extension}")
|
|
104
|
+
|
|
105
|
+
def accept
|
|
106
|
+
loop do
|
|
107
|
+
socket = @server.accept
|
|
108
|
+
next socket.close unless socket.getpeereid.first == Process.euid
|
|
109
|
+
|
|
110
|
+
attach(socket)
|
|
111
|
+
end
|
|
112
|
+
rescue IOError
|
|
113
|
+
nil
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def attach(socket)
|
|
117
|
+
client = Connection.new(socket, on_hang_up: -> { detach(client) })
|
|
118
|
+
# Under the lock that turns start and end under, so the turn the hello
|
|
119
|
+
# names cannot end unseen.
|
|
120
|
+
@lock.synchronize do
|
|
121
|
+
client.write({ type: "hello", protocol: PROTOCOL, session: @name, cwd: Dir.pwd, **@running.to_h }.compact)
|
|
122
|
+
@terminal.open_prompts.each { client.write(it) }
|
|
123
|
+
@clients.add(client)
|
|
124
|
+
end
|
|
125
|
+
Thread.new { read_messages(client) }
|
|
126
|
+
end
|
|
127
|
+
|
|
64
128
|
# The end of input means the client is done sending, not gone: the
|
|
65
|
-
# turns
|
|
66
|
-
def read_messages
|
|
67
|
-
while (message = next_message)
|
|
68
|
-
dispatch(message)
|
|
129
|
+
# turns it queued still run and reply before it is let go.
|
|
130
|
+
def read_messages(client)
|
|
131
|
+
while (message = next_message(client))
|
|
132
|
+
dispatch(message, client)
|
|
69
133
|
end
|
|
70
134
|
ensure
|
|
71
|
-
@
|
|
135
|
+
@lock.synchronize { @leaving << client }
|
|
136
|
+
release
|
|
72
137
|
end
|
|
73
138
|
|
|
74
|
-
def next_message
|
|
75
|
-
|
|
139
|
+
def next_message(client)
|
|
140
|
+
client.read
|
|
76
141
|
rescue ArgumentError => e
|
|
77
|
-
|
|
142
|
+
client.write(type: "error", text: e.message)
|
|
78
143
|
retry
|
|
79
144
|
end
|
|
80
145
|
|
|
81
|
-
def dispatch(message)
|
|
146
|
+
def dispatch(message, client)
|
|
82
147
|
# A missing answer, as at Ctrl-D, stays nil and refuses.
|
|
83
148
|
if message.key?("answer") then @terminal.answer(message["id"], message["answer"]&.to_s)
|
|
84
149
|
elsif message["interrupt"] then Process.kill("INT", 0)
|
|
85
|
-
elsif message.key?("prompt") then
|
|
150
|
+
elsif message.key?("prompt") then queue(message["prompt"].to_s, client)
|
|
86
151
|
end
|
|
87
152
|
end
|
|
88
153
|
|
|
154
|
+
# Numbers the turn and tells the client which one is its own.
|
|
155
|
+
def queue(text, client)
|
|
156
|
+
@lock.synchronize do
|
|
157
|
+
turn = @pending[client] = @queued += 1
|
|
158
|
+
client.write(type: "queued", turn: turn)
|
|
159
|
+
@prompts << [turn, text]
|
|
160
|
+
end
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
# Lets go of the clients that are done sending once their turns are done.
|
|
164
|
+
def release
|
|
165
|
+
done = @lock.synchronize do
|
|
166
|
+
finished, @leaving = @leaving.partition { (@pending[it] || 0) <= @finished }
|
|
167
|
+
finished
|
|
168
|
+
end
|
|
169
|
+
done.each { detach(it) }
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
def detach(client)
|
|
173
|
+
@lock.synchronize do
|
|
174
|
+
@pending.delete(client)
|
|
175
|
+
@leaving.delete(client)
|
|
176
|
+
end
|
|
177
|
+
client.close
|
|
178
|
+
@clients.remove(client)
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
# A plain worker stops, with its commands, when its client is gone.
|
|
182
|
+
def clients_changed(size)
|
|
183
|
+
return write_sidecar if @server
|
|
184
|
+
|
|
185
|
+
Process.kill("TERM", 0) if size.zero?
|
|
186
|
+
end
|
|
187
|
+
|
|
89
188
|
def turns
|
|
90
189
|
loop do
|
|
91
|
-
text = @prompts.pop
|
|
92
|
-
turn
|
|
190
|
+
turn, text = @prompts.pop
|
|
191
|
+
run_turn(turn, text)
|
|
93
192
|
rescue Interrupt
|
|
94
193
|
next # sent while no turn was running
|
|
95
194
|
end
|
|
96
195
|
end
|
|
97
196
|
|
|
98
|
-
def turn
|
|
197
|
+
def run_turn(turn, text)
|
|
198
|
+
start(turn, text)
|
|
99
199
|
reply = text.start_with?("/") ? command(text) : @session.turn(text)
|
|
100
|
-
done(reply: reply.to_s)
|
|
200
|
+
done(turn, reply: reply.to_s)
|
|
101
201
|
rescue Interrupt
|
|
102
|
-
done(interrupted: true)
|
|
202
|
+
done(turn, interrupted: true)
|
|
103
203
|
rescue StandardError, ScriptError => e
|
|
104
|
-
@
|
|
105
|
-
done
|
|
204
|
+
@clients.write(type: "error", text: e.message)
|
|
205
|
+
done(turn)
|
|
106
206
|
end
|
|
107
207
|
|
|
108
|
-
def
|
|
109
|
-
@
|
|
208
|
+
def start(turn, text)
|
|
209
|
+
@lock.synchronize do
|
|
210
|
+
@running = { turn: turn, prompt: text }
|
|
211
|
+
@clients.write(type: "turn", turn: turn, prompt: text)
|
|
212
|
+
end
|
|
213
|
+
write_sidecar
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
def done(turn, reply: "", interrupted: false)
|
|
217
|
+
@lock.synchronize do
|
|
218
|
+
@running = nil
|
|
219
|
+
@finished = turn
|
|
220
|
+
@clients.write(type: "done", turn: turn, reply: reply, interrupted: interrupted)
|
|
221
|
+
end
|
|
222
|
+
write_sidecar
|
|
223
|
+
release
|
|
110
224
|
end
|
|
111
225
|
|
|
112
226
|
def command(line)
|
|
@@ -116,6 +230,39 @@ module Elelem
|
|
|
116
230
|
|
|
117
231
|
@terminal.say(@session.commands.names.join(" "))
|
|
118
232
|
end
|
|
233
|
+
|
|
234
|
+
# Ends a session that has been idle with nobody attached. A turn that
|
|
235
|
+
# waits on a prompt counts as idle: nobody is there to answer it.
|
|
236
|
+
def watch
|
|
237
|
+
tick = [@idle / 4.0, 5].min
|
|
238
|
+
quiet = 0
|
|
239
|
+
loop do
|
|
240
|
+
sleep tick
|
|
241
|
+
quiet = idle? ? quiet + tick : 0
|
|
242
|
+
return Process.kill("TERM", 0) if quiet >= @idle
|
|
243
|
+
end
|
|
244
|
+
end
|
|
245
|
+
|
|
246
|
+
def idle? = @clients.empty? && @prompts.empty? && (@running.nil? || @terminal.asking?)
|
|
247
|
+
|
|
248
|
+
# What `elelemd ls` shows, so it needs no connection.
|
|
249
|
+
def write_sidecar
|
|
250
|
+
return unless @server
|
|
251
|
+
|
|
252
|
+
info = { name: @name, pid: Process.pid, cwd: Dir.pwd, **@info, busy: !@running.nil?,
|
|
253
|
+
clients: @clients.size, started: @started }.compact
|
|
254
|
+
@lock.synchronize do
|
|
255
|
+
File.write(path("json.tmp"), JSON.generate(info), perm: 0o600)
|
|
256
|
+
File.rename(path("json.tmp"), path("json"))
|
|
257
|
+
end
|
|
258
|
+
end
|
|
259
|
+
|
|
260
|
+
def close_session
|
|
261
|
+
return unless @server
|
|
262
|
+
|
|
263
|
+
@server.close
|
|
264
|
+
FileUtils.rm_f([path("sock"), path("json")])
|
|
265
|
+
end
|
|
119
266
|
end
|
|
120
267
|
end
|
|
121
268
|
end
|