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.
data/lib/elelem/daemon.rb CHANGED
@@ -3,10 +3,12 @@
3
3
  require "elelem"
4
4
  require "fileutils"
5
5
  require "json"
6
+ require "monitor"
6
7
  require "socket"
7
8
 
8
9
  require_relative "daemon/version"
9
10
  require_relative "daemon/connection"
11
+ require_relative "daemon/clients"
10
12
  require_relative "daemon/terminal"
11
13
  require_relative "daemon/worker"
12
14
  require_relative "daemon/client"
@@ -29,13 +31,40 @@ module Elelem
29
31
  end
30
32
  end
31
33
 
34
+ # Named sessions keep their sockets and sidecars next to the daemon's.
35
+ def self.sessions_dir(path = socket_path) = File.join(File.dirname(path), "sessions")
36
+
37
+ # The sidecars of the sessions that are running. A session holds its lock
38
+ # until it exits, so a sidecar left by one that crashed is skipped.
39
+ def self.sessions(dir = sessions_dir)
40
+ Dir[File.join(dir, "*.json")].filter_map do |file|
41
+ JSON.parse(File.read(file)) if held?("#{file.delete_suffix(".json")}.lock")
42
+ rescue JSON::ParserError, SystemCallError
43
+ nil
44
+ end
45
+ end
46
+
47
+ def self.held?(lock)
48
+ File.open(lock, File::RDWR) { !it.flock(File::LOCK_EX | File::LOCK_NB) }
49
+ rescue Errno::ENOENT
50
+ false
51
+ end
52
+
53
+ def self.private_umask
54
+ old = File.umask(0o177)
55
+ yield
56
+ ensure
57
+ File.umask(old)
58
+ end
59
+
32
60
  attr_reader :path
33
61
 
34
62
  def initialize(path: self.class.socket_path, provider: ENV.fetch("ELELEM_PROVIDER", "demo"),
35
- max_workers: MAX_WORKERS)
63
+ max_workers: MAX_WORKERS, idle: Worker::IDLE)
36
64
  @path = path
37
65
  @provider = provider
38
66
  @max_workers = max_workers
67
+ @idle = idle
39
68
  @workers = {}
40
69
  end
41
70
 
@@ -55,7 +84,7 @@ module Elelem
55
84
  FileUtils.mkdir_p(File.dirname(@path), mode: 0o700)
56
85
  lock
57
86
  FileUtils.rm_f(@path) # a socket left by a daemon that died; the lock says none is running
58
- @server = private_umask { UNIXServer.new(@path) }
87
+ @server = self.class.private_umask { UNIXServer.new(@path) }
59
88
  preload
60
89
  end
61
90
 
@@ -75,13 +104,6 @@ module Elelem
75
104
  raise "elelemd is already running on #{@path}" unless @lock.flock(File::LOCK_EX | File::LOCK_NB)
76
105
  end
77
106
 
78
- def private_umask
79
- old = File.umask(0o177)
80
- yield
81
- ensure
82
- File.umask(old)
83
- end
84
-
85
107
  # Loads the provider's code, but not plugins, so workers share it.
86
108
  def preload
87
109
  require "elelem/#{@provider}"
@@ -113,7 +135,8 @@ module Elelem
113
135
  pid = fork do
114
136
  @server.close
115
137
  @lock.close
116
- Worker.new(socket, provider: @provider, status: status).run
138
+ Worker.new(socket, provider: @provider, status: status, sessions: self.class.sessions_dir(@path),
139
+ idle: @idle).run
117
140
  end
118
141
  lead_group(pid)
119
142
  @workers[pid] = Process.detach(pid)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: elelem-daemon
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - mo khan
@@ -51,29 +51,15 @@ executables:
51
51
  extensions: []
52
52
  extra_rdoc_files: []
53
53
  files:
54
- - ".agents/backlog/001-named-sessions.md"
55
- - ".agents/backlog/002-agent-to-agent.md"
56
- - ".github/workflows/release.yml"
57
- - ".release-please-manifest.json"
58
- - ".rspec"
59
- - ".rubocop.yml"
60
- - CHANGELOG.md
61
54
  - LICENSE.txt
62
- - README.md
63
- - Rakefile
64
55
  - exe/elelemd
65
56
  - lib/elelem/daemon.rb
66
57
  - lib/elelem/daemon/client.rb
58
+ - lib/elelem/daemon/clients.rb
67
59
  - lib/elelem/daemon/connection.rb
68
60
  - lib/elelem/daemon/terminal.rb
69
61
  - lib/elelem/daemon/version.rb
70
62
  - lib/elelem/daemon/worker.rb
71
- - release-please-config.json
72
- - spec/elelem/daemon/client_spec.rb
73
- - spec/elelem/daemon/connection_spec.rb
74
- - spec/elelem/daemon/terminal_spec.rb
75
- - spec/elelem/daemon_spec.rb
76
- - spec/spec_helper.rb
77
63
  homepage: https://elelem.sh
78
64
  licenses:
79
65
  - MIT
@@ -1,19 +0,0 @@
1
- As a `developer`, I `want a session that outlives its connection`, so
2
- that `I can detach from a long task and reattach later, as with screen`.
3
-
4
- # SYNOPSIS
5
-
6
- `{"session":"deploy"}` attaches to a long-lived worker by name.
7
-
8
- # DESCRIPTION
9
-
10
- Today a connection is a session: closing it ends the worker. A named
11
- session is a worker with its own socket, `sessions/NAME.sock`, next to
12
- `elelemd.sock`, which is how screen does it.
13
-
14
- - Every attached client gets each event. A prompt stays open until some
15
- client answers it.
16
- - The worker exits after an idle timeout with no client attached.
17
- - `elelemd attach NAME` and `elelemd ls`.
18
- - A sidecar `sessions/NAME.json` records the folder, the provider and
19
- whether a turn is running, so `ls` needs no connection.
@@ -1,23 +0,0 @@
1
- As an `agent working in one repo`, I `want to ask an agent in another
2
- repo`, so that `agents can share what they know about their own code`.
3
-
4
- # SYNOPSIS
5
-
6
- A one-file plugin adds the tools `agents` and `ask_agent(name, prompt)`.
7
-
8
- # DESCRIPTION
9
-
10
- Depends on 001. The sessions directory is the registry: `agents` lists
11
- the sidecar files, and `ask_agent` connects to that session's socket
12
- and returns its `done` reply. Asking with `cwd` instead of a name
13
- starts a fresh agent in that folder through `elelemd.sock`, which works
14
- today.
15
-
16
- - Approvals: the peer's `prompt` events go to the person at the top of
17
- the chain. The asking agent never answers them itself.
18
- - Loops: each request carries `from` and `via`. The daemon refuses a
19
- request whose `via` already names the target, or holds more than 3
20
- hops.
21
- - Trust: the peer's reply reaches the model as data, framed as "reply
22
- from agent NAME in PATH", not as instructions.
23
- - Cost: cap the turns per request.
@@ -1,63 +0,0 @@
1
- name: Release
2
-
3
- on:
4
- push:
5
- branches: [main]
6
- workflow_dispatch:
7
-
8
- permissions: {}
9
-
10
- concurrency:
11
- group: release
12
- cancel-in-progress: false
13
-
14
- jobs:
15
- test:
16
- runs-on: ubuntu-latest
17
- permissions:
18
- contents: read
19
- steps:
20
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
21
- with:
22
- persist-credentials: false
23
- - uses: ruby/setup-ruby@3ff19f5e2baf30647122352b96108b1fbe250c64 # v1.299.0
24
- with:
25
- ruby-version: "4.0"
26
- bundler-cache: true
27
- - run: bin/test
28
- - run: bin/lint
29
-
30
- release-please:
31
- needs: test
32
- runs-on: ubuntu-latest
33
- permissions:
34
- contents: write
35
- issues: write
36
- pull-requests: write
37
- outputs:
38
- release_created: ${{ steps.release.outputs.release_created }}
39
- steps:
40
- - id: release
41
- uses: googleapis/release-please-action@45996ed1f6d02564a971a2fa1b5860e934307cf7 # v5.0.0
42
- with:
43
- config-file: release-please-config.json
44
- manifest-file: .release-please-manifest.json
45
-
46
- publish:
47
- needs: release-please
48
- if: needs.release-please.outputs.release_created == 'true'
49
- runs-on: ubuntu-latest
50
- permissions:
51
- contents: write
52
- id-token: write
53
- steps:
54
- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
55
- with:
56
- persist-credentials: false
57
- - uses: ruby/setup-ruby@3ff19f5e2baf30647122352b96108b1fbe250c64 # v1.299.0
58
- with:
59
- ruby-version: "4.0"
60
- bundler-cache: true
61
- - uses: rubygems/release-gem@7f9650160c1a4e7989fdc9855807bdbd421d8b6b # v1.4.1
62
- with:
63
- await-release: false
@@ -1,3 +0,0 @@
1
- {
2
- ".": "0.1.0"
3
- }
data/.rspec DELETED
@@ -1 +0,0 @@
1
- --require spec_helper
data/.rubocop.yml DELETED
@@ -1,62 +0,0 @@
1
- AllCops:
2
- NewCops: enable
3
- TargetRubyVersion: 4.0
4
- SuggestExtensions: false
5
- Exclude:
6
- - "pkg/**/*"
7
- - "bin/**/*"
8
- - "vendor/**/*"
9
- - "fixtures/**/*"
10
-
11
- Metrics:
12
- Enabled: false
13
-
14
- Naming/PredicateMethod:
15
- AllowedMethods:
16
- - call
17
- - run
18
- - summarize
19
- - prompt
20
-
21
- Naming/MethodParameterName:
22
- AllowedNames:
23
- - me
24
- - id
25
- - as
26
- - io
27
-
28
- Style/GlobalVars:
29
- Exclude:
30
- - "spec/**/*"
31
-
32
- Lint/EmptyBlock:
33
- Exclude:
34
- - "spec/**/*"
35
-
36
- Lint/UselessDefaultValueArgument:
37
- Enabled: false
38
-
39
- Lint/RedundantRequireStatement:
40
- Enabled: false
41
-
42
- Lint/UnusedBlockArgument:
43
- IgnoreEmptyBlocks: true
44
- AllowUnusedKeywordArguments: true
45
-
46
- Style/Documentation:
47
- Enabled: false
48
-
49
- Style/FormatStringToken:
50
- Enabled: false
51
-
52
- Style/FrozenStringLiteralComment:
53
- Enabled: true
54
-
55
- Style/StringLiterals:
56
- EnforcedStyle: double_quotes
57
-
58
- Style/StringLiteralsInInterpolation:
59
- EnforcedStyle: double_quotes
60
-
61
- Layout/LineLength:
62
- Max: 120
data/CHANGELOG.md DELETED
@@ -1,10 +0,0 @@
1
- # Changelog
2
-
3
- ## 0.1.0 (2026-11-21)
4
-
5
-
6
- ### Features
7
-
8
- * serve elelem sessions over a unix socket, one worker per connection ([1493fdd](https://github.com/elelem-sh/daemon/commit/1493fdddf94c44e7eb9a47d8c93571360debf027))
9
-
10
- ## Changelog
data/README.md DELETED
@@ -1,106 +0,0 @@
1
- # elelem-daemon
2
-
3
- An always-on [elelem](https://elelem.sh) that you talk to over a Unix socket.
4
-
5
- `elelemd` runs once per user. Each connection gets its own worker process. The
6
- worker moves into the folder the client names, so that folder's plugins,
7
- permissions and `AGENTS.md` apply. A crash in one folder doesn't affect another.
8
-
9
- ```sh
10
- gem install elelem-daemon
11
- elelemd serve -p ollama # in a terminal, or as a service (below)
12
-
13
- elelemd ask "why does the build fail?" # a prompt for this folder
14
- elelemd chat # a conversation from this folder
15
- ```
16
-
17
- The socket is `$XDG_RUNTIME_DIR/elelem/elelemd.sock`, or
18
- `~/.local/state/elelem/elelemd.sock` when that variable isn't set. Set
19
- `ELELEM_SOCKET` or pass `--socket` to use another path. Only your user can
20
- connect.
21
-
22
- ## Protocol
23
-
24
- Each line is one JSON object, in both directions. The daemon speaks first.
25
-
26
- ```
27
- < {"type":"hello","protocol":1}
28
- > {"cwd":"/src/app","prompt":"run the specs","interactive":false}
29
- < {"type":"tool","name":"execute","args":{"command":"bin/test"},"state":"+"}
30
- < {"type":"content","text":"..."}
31
- < {"type":"done","reply":"...","interrupted":false}
32
- ```
33
-
34
- The first request must include `cwd`, an absolute folder. It may also include:
35
- - `provider` and `model`;
36
- - `env`, which the worker adds to its environment;
37
- - `interactive`, which says whether a person will answer prompts.
38
-
39
- After the first request you can send any of these:
40
- - `{"prompt":"..."}` starts another turn in the same conversation. Prompts sent
41
- while a turn is running wait their turn.
42
- - `{"id":1,"answer":"y"}` answers a `prompt` event. `null` refuses.
43
- - `{"interrupt":true}` stops the running turn and the command it is running.
44
-
45
- Instead of a request, `{"status":true}` gets the daemon's pid, worker count and
46
- version.
47
-
48
- The daemon sends `content`, `thinking`, `tool`, `prompt` and `error` events,
49
- and exactly one `done` for each prompt. Closing your sending side means you are
50
- done sending: the queued turns still finish and reply. Closing the connection
51
- stops the worker.
52
-
53
- The simplest client is `nc` (OpenBSD `nc` needs `-N` to close its side when its
54
- input ends):
55
-
56
- ```sh
57
- printf '%s\n' "{\"cwd\":\"$PWD\",\"prompt\":\"hi\"}" | nc -N -U "$XDG_RUNTIME_DIR/elelem/elelemd.sock"
58
- ```
59
-
60
- ## Approvals
61
-
62
- A tool that needs approval (`"ask"` in `permissions.json`) asks the client with
63
- a `prompt` event. If the client isn't interactive, such as a script or
64
- `elelemd ask` without a terminal, the daemon denies the tool. It never approves
65
- on its own.
66
-
67
- ## As a service
68
-
69
- systemd, as `~/.config/systemd/user/elelemd.service`:
70
-
71
- ```ini
72
- [Unit]
73
- Description=elelem daemon
74
-
75
- [Service]
76
- ExecStart=%h/.local/share/gem/ruby/4.0.0/bin/elelemd serve -p anthropic
77
- EnvironmentFile=-%h/.config/elelem/env
78
- Restart=on-failure
79
-
80
- [Install]
81
- WantedBy=default.target
82
- ```
83
-
84
- Then run `systemctl --user enable --now elelemd`.
85
-
86
- launchd, as `~/Library/LaunchAgents/sh.elelem.elelemd.plist`:
87
-
88
- ```xml
89
- <plist version="1.0"><dict>
90
- <key>Label</key><string>sh.elelem.elelemd</string>
91
- <key>ProgramArguments</key><array><string>/usr/local/bin/elelemd</string><string>serve</string></array>
92
- <key>RunAtLoad</key><true/>
93
- <key>KeepAlive</key><true/>
94
- </dict></plist>
95
- ```
96
-
97
- Then run `launchctl load ~/Library/LaunchAgents/sh.elelem.elelemd.plist`.
98
-
99
- `elelemd ask` and `elelemd chat` send your shell's environment with each
100
- request, so commands run with your `PATH` and keys, not only the service's.
101
-
102
- ## Limits
103
-
104
- - Each connection starts its own MCP servers, so a single `ask` is about as
105
- fast as `elelem ask`. Long conversations are where the daemon pays off.
106
- - Not available on Windows, which has no `fork`.
data/Rakefile DELETED
@@ -1,8 +0,0 @@
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]
@@ -1,12 +0,0 @@
1
- {
2
- "packages": {
3
- ".": {
4
- "release-type": "ruby",
5
- "package-name": "elelem-daemon",
6
- "version-file": "lib/elelem/daemon/version.rb",
7
- "bump-minor-pre-major": true,
8
- "initial-version": "0.1.0",
9
- "include-component-in-tag": false
10
- }
11
- }
12
- }
@@ -1,88 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- RSpec.describe Elelem::Daemon::Client do
4
- # A person at a terminal who gives these answers, then ends input.
5
- let(:person_class) do
6
- Class.new do
7
- attr_reader :asked
8
-
9
- def initialize(*answers)
10
- @answers = answers
11
- @asked = []
12
- end
13
-
14
- def interactive? = true
15
- def remember(_line) = nil
16
-
17
- def ask(prompt)
18
- @asked << prompt
19
- @answers.shift
20
- end
21
- end
22
- end
23
-
24
- around do |example|
25
- Dir.mktmpdir("elelemd") do |dir|
26
- @path = File.join(dir, "elelemd.sock")
27
- @folder = File.join(dir, "app")
28
- FileUtils.mkdir_p(File.join(@folder, ".agents", "plugins"))
29
- example.run
30
- end
31
- end
32
-
33
- before do
34
- allow($stdout).to receive(:puts)
35
- daemon = Elelem::Daemon.new(path: @path)
36
- @thread = Thread.new { daemon.start }
37
- Thread.pass until File.socket?(@path)
38
- end
39
-
40
- after { @thread.kill.join }
41
-
42
- let(:screen) { StringIO.new }
43
-
44
- def client(input = Elelem::NullInput.new)
45
- described_class.new(path: @path, input: input, output: Elelem::Output.new(stream: screen))
46
- end
47
-
48
- it "sends one prompt for this folder and returns the reply" do
49
- expect(client.ask("pwd", cwd: @folder)).to eq("exit 0")
50
- expect(screen.string).to include("execute", File.realpath(@folder))
51
- end
52
-
53
- it "sends this process's environment" do
54
- ENV["SPEC_GREETING"] = "howdy"
55
- client.ask("echo $SPEC_GREETING", cwd: @folder)
56
- expect(screen.string).to include("howdy")
57
- ensure
58
- ENV.delete("SPEC_GREETING")
59
- end
60
-
61
- it "holds a conversation, one prompt per line" do
62
- client(person_class.new("true", "", "false", nil)).chat(cwd: @folder)
63
- expect(screen.string).to include("exit 0", "exit 1")
64
- end
65
-
66
- it "answers approval prompts with the person's answer" do
67
- File.write(File.join(@folder, ".agents", "plugins", "ask.rb"), <<~RUBY)
68
- Elelem.configure do |config|
69
- config.setup(:ask) do |session|
70
- session.commands.register("ask", description: "spec") { session.output.say("got " + session.input.ask("Allow?").inspect) }
71
- end
72
- end
73
- RUBY
74
- person = person_class.new("/ask", "y", nil)
75
- client(person).chat(cwd: @folder)
76
- expect(person.asked).to eq(["> ", "Allow?", "> "])
77
- expect(screen.string).to include('got "y"')
78
- end
79
-
80
- it "shows the daemon's error" do
81
- expect { client.ask("pwd", cwd: @folder, provider: "nope") }.to raise_error(RuntimeError, /unknown provider/)
82
- end
83
-
84
- it "says when the daemon is not running" do
85
- @thread.kill.join
86
- expect { client.ask("pwd") }.to raise_error(RuntimeError, /elelemd is not running/)
87
- end
88
- end
@@ -1,40 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- RSpec.describe Elelem::Daemon::Connection do
4
- let(:pair) { UNIXSocket.pair }
5
- let(:ours) { described_class.new(pair[0]) }
6
- let(:theirs) { pair[1] }
7
-
8
- after { pair.each(&:close) }
9
-
10
- it "writes one JSON object per line" do
11
- ours.write(type: "done", reply: "a\nb")
12
- expect(theirs.gets).to eq(%({"type":"done","reply":"a\\nb"}\n))
13
- end
14
-
15
- it "reads objects until the end" do
16
- theirs.write(%({"prompt":"hi"}\n{"interrupt":true}))
17
- theirs.close_write
18
- expect([ours.read, ours.read, ours.read]).to eq([{ "prompt" => "hi" }, { "interrupt" => true }, nil])
19
- end
20
-
21
- it "refuses a line that is not a JSON object" do
22
- theirs.write("[1]\nnope\n")
23
- expect { ours.read }.to raise_error(ArgumentError, "expected a JSON object")
24
- expect { ours.read }.to raise_error(ArgumentError, "expected a JSON object")
25
- end
26
-
27
- it "refuses a line that is too long" do
28
- stub_const("#{described_class}::LINE_LIMIT", 8)
29
- theirs.write(%({"prompt":"far too long"}\n))
30
- expect { ours.read }.to raise_error(ArgumentError, /longer than 8 bytes/)
31
- end
32
-
33
- it "tells its owner when the other end has gone" do
34
- hung_up = false
35
- connection = described_class.new(pair[0], on_hang_up: -> { hung_up = true })
36
- theirs.close
37
- connection.write(type: "content", text: "x" * 100_000)
38
- expect(hung_up).to be(true)
39
- end
40
- end
@@ -1,44 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- RSpec.describe Elelem::Daemon::Terminal do
4
- let(:events) { [] }
5
- let(:connection) { instance_double(Elelem::Daemon::Connection).tap { |c| allow(c).to receive(:write) { events << it } } }
6
-
7
- def terminal(interactive: true) = described_class.new(connection, interactive:)
8
-
9
- it "always reports itself interactive, so approvals are asked for, not skipped" do
10
- expect(terminal(interactive: false)).to be_interactive
11
- end
12
-
13
- it "sends text as plain content" do
14
- terminal.say("\e[36mhi\e[0m", as: :markdown)
15
- terminal.print("more")
16
- terminal.thinking("hmm")
17
- terminal.say(" ")
18
- expect(events).to eq([{ type: "content", text: "hi", as: "markdown" }, { type: "content", text: "more" },
19
- { type: "thinking", text: "hmm" }])
20
- end
21
-
22
- it "sends tool calls as their own event" do
23
- terminal.doing("execute", { "command" => "ls" }, state: "x")
24
- expect(events).to eq([{ type: "tool", name: "execute", args: { "command" => "ls" }, state: "x" }])
25
- end
26
-
27
- it "waits for the answer to a prompt" do
28
- t = terminal
29
- answer = Thread.new { t.ask("Allow?") }
30
- Thread.pass until events.any?
31
- t.answer(events.last[:id], "y")
32
- expect(answer.value).to eq("y")
33
- expect(events).to eq([{ type: "prompt", id: 1, text: "Allow?" }])
34
- end
35
-
36
- it "asks nothing of a client that cannot answer, which denies" do
37
- expect(terminal(interactive: false).ask("Allow?")).to be_nil
38
- expect(events).to be_empty
39
- end
40
-
41
- it "ignores an answer to no open prompt" do
42
- expect { terminal.answer(7, "y") }.not_to raise_error
43
- end
44
- end