agent-chat 1.0.2 → 2.0.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.
Files changed (67) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +120 -0
  3. data/LICENSE +21 -0
  4. data/README.md +196 -0
  5. data/config.ru +1 -6
  6. data/exe/agent-chat +3 -2
  7. data/exe/agent-chat-web +4 -7
  8. data/lib/agent_chat/chat/draft.rb +24 -0
  9. data/lib/agent_chat/chat/entrance.rb +34 -0
  10. data/lib/agent_chat/chat/missing_ids.rb +12 -0
  11. data/lib/agent_chat/chat.rb +56 -0
  12. data/lib/agent_chat/cli/arrival_notices.rb +29 -0
  13. data/lib/agent_chat/cli/command_line.rb +37 -0
  14. data/lib/agent_chat/cli/commands.rb +51 -0
  15. data/lib/agent_chat/cli/flag_values.rb +49 -0
  16. data/lib/agent_chat/cli/help.rb +62 -0
  17. data/lib/agent_chat/cli/json_output.rb +50 -0
  18. data/lib/agent_chat/cli/lookup.rb +24 -0
  19. data/lib/agent_chat/cli/notice.rb +10 -0
  20. data/lib/agent_chat/cli/parse.rb +17 -0
  21. data/lib/agent_chat/cli/request.rb +9 -0
  22. data/lib/agent_chat/cli/request_builder.rb +41 -0
  23. data/lib/agent_chat/cli/runner.rb +75 -0
  24. data/lib/agent_chat/cli/stream.rb +37 -0
  25. data/lib/agent_chat/cli/text_output.rb +48 -0
  26. data/lib/agent_chat/cli/tokenizer.rb +66 -0
  27. data/lib/agent_chat/cli/vocabulary.rb +25 -0
  28. data/lib/agent_chat/cli/wording.rb +42 -0
  29. data/lib/agent_chat/global_id.rb +10 -0
  30. data/lib/agent_chat/message.rb +6 -11
  31. data/lib/agent_chat/outcome.rb +4 -0
  32. data/lib/agent_chat/problem.rb +15 -0
  33. data/lib/agent_chat/room/arrival.rb +9 -0
  34. data/lib/agent_chat/room/directory.rb +27 -0
  35. data/lib/agent_chat/room/location.rb +21 -0
  36. data/lib/agent_chat/room/name.rb +19 -0
  37. data/lib/agent_chat/room/opener.rb +63 -0
  38. data/lib/agent_chat/room/schema.rb +50 -0
  39. data/lib/agent_chat/room/sqlite.rb +8 -0
  40. data/lib/agent_chat/room/store.rb +87 -0
  41. data/lib/agent_chat/spelling.rb +43 -0
  42. data/lib/agent_chat/version.rb +1 -1
  43. data/lib/agent_chat/web/app.rb +53 -18
  44. data/lib/agent_chat/web/post_body.rb +33 -0
  45. data/lib/agent_chat.rb +2 -8
  46. data/public/css/form.css +3 -3
  47. data/public/css/replies.css +110 -0
  48. data/public/css/style.css +1 -0
  49. data/public/index.html +31 -3
  50. data/public/js/feed/message_feed.js +24 -0
  51. data/public/js/feed/message_view.js +41 -0
  52. data/public/js/feed/reply_link.js +24 -0
  53. data/public/js/messages.js +19 -34
  54. data/public/js/page.js +13 -0
  55. data/public/js/reply_chips.js +21 -0
  56. data/public/js/reply_selection.js +23 -0
  57. metadata +70 -46
  58. data/lib/agent_chat/argument_parser.rb +0 -20
  59. data/lib/agent_chat/cli_adapter.rb +0 -82
  60. data/lib/agent_chat/message_formatter.rb +0 -14
  61. data/lib/agent_chat/persistence/database.rb +0 -112
  62. data/lib/agent_chat/persistence/file_resolver.rb +0 -14
  63. data/lib/agent_chat/persistence.rb +0 -19
  64. data/lib/agent_chat/service/main.rb +0 -70
  65. data/lib/agent_chat/web/room_discovery_service.rb +0 -18
  66. data/lib/agent_chat/web/service_factory.rb +0 -13
  67. data/public/js/message_feed.js +0 -48
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 44d921a99e0a179d25c6655395dfd410fb961e04f99ab43acff8e18020657b7f
4
- data.tar.gz: 06aff39572e55e0b66d74416417c1c518ad4ef1ab215b37ee27ebdd688c8a69a
3
+ metadata.gz: c8733ff9d0f8c38fb32cdd2f5b537d77ece30f1647e613f6c391081194cd2ca1
4
+ data.tar.gz: 801571bd84314e3fbaeecc535c56cb1ce7f0390f0b1a2a549154b9e21a5950fa
5
5
  SHA512:
6
- metadata.gz: b4796042154656caa2dd61a51192987b557c73d8c3c2c99b3cedce7f3d0c5e3cd327baf30ee66b3e667e016d10f2f053419684f3e8a5edd680a2155b665e64fe
7
- data.tar.gz: 981ea146b4142bbcff350c1f38a6f5cd9b0c8af91b519086ff0b8d8726a83527efd4f8d551bddee2fb91689f674d47344efd971eeb1e800ed70c7a99c4b40446
6
+ metadata.gz: c04884b2c84892b86520dc58b69dd5551106a1e5434df2f6ce31b6ba6fa46021e9b50108bc18de233212e07c3bbdad041709f871b2cbfbfd482c9790e691b069
7
+ data.tar.gz: f96ea41e4a33279827a75fd55ada023865ad400de13347fd7076cc309dd0092146b2a20c5d006dda9a840bcc7653e207ad05a80a0266e315a8dd88912991b26b
data/CHANGELOG.md ADDED
@@ -0,0 +1,120 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [2.0.0] - 2026-11-22
9
+
10
+ ### Breaking
11
+ - Ruby 3.3 or later is required. Ruby 3.2 is no longer supported.
12
+ - Rooms written by 1.x are not read. The first 2.0 command to open such a
13
+ room moves its database to `$TMPDIR/agent-chat/backups/<UTC time>/<room>/`
14
+ and starts the room empty, with a `room_reset` warning naming the backup.
15
+ Later schema changes will do the same rather than migrate.
16
+ - `send` now prints the id the new message was given. It used to print
17
+ nothing.
18
+ - Unknown flags and commands are no longer ignored. One edit from exactly
19
+ one known name, or differing only in case, underscores or dashes, they are
20
+ read as that name with a warning; otherwise the command is refused with
21
+ exit status 2. A flag the command does not take is ignored with a warning.
22
+ A missing `--room`, `--author` or `--consumer`, or a flag without its
23
+ value, is refused instead of failing deep inside.
24
+ - The text header gains the message id and, for replies, the ids answered:
25
+ `<<< Alice | 2026-11-22 14:30:00 | 7xKqR2m | re: 3fGhJ9k >>>`.
26
+ - `receive` prints nothing when there is nothing new. It used to print an
27
+ empty line.
28
+ - `send` refuses empty content and strips the newline `echo` adds.
29
+ - Room names must be plain folder names: no `/`, `\`, control characters,
30
+ `.` or `..`.
31
+ - The web API answers a POST with 201 and a JSON body, refuses a body not
32
+ labelled `application/json` with 415, and requires `consumer` on
33
+ `/messages/new`.
34
+
35
+ ### Added
36
+ - Every message has a random 7-character base58 id.
37
+ - `send --reply-to <id>` links a message to the messages it answers. Repeat
38
+ the flag or separate ids with commas. An unknown id refuses the whole
39
+ message and nothing is saved.
40
+ - `--json` on every command. Messages are one JSON object per line with
41
+ `id`, `author`, `timestamp` (UTC), `content` and `reply_to`. `send` prints
42
+ `{"status":"accepted","assigned_id":...}`. A refused request prints
43
+ `{"status":"rejected","error":{"code":...,"message":...}}` and exits 1.
44
+ Notes and warnings go to standard error as JSON lines.
45
+ - `show --room <name> <id>...` prints messages by id.
46
+ - `--all` on `receive` and `stream` reads the whole history without moving
47
+ any read position.
48
+ - Reading a room that does not exist says that it created the room, and
49
+ names an existing room one edit away.
50
+ - The web UI shows message ids and reply links that jump to the message
51
+ answered, and lets you reply to several messages at once.
52
+ - The web API returns `id` and `reply_to`, accepts `reply_to` on POST, and
53
+ reports problems with the same error object as the CLI (400, or 422 for
54
+ unknown ids).
55
+
56
+ ### Fixed
57
+ - Pressing Ctrl-C just after `stream` or `receive` started crashed Ruby with
58
+ a `[BUG]` report. The interrupt landed while sqlite3 was loading Ruby's
59
+ UTF-16 encodings on its first query. They are now loaded before any query,
60
+ and `stream` stops with status 0.
61
+ - The web UI rendered message content as unsanitised HTML, so any message
62
+ could run script in the viewer's browser. Content is now sanitised.
63
+ - The web UI dropped a message posted in the same second as another,
64
+ because it compared timestamps.
65
+ - The web UI rebuilt the whole feed on every poll, reloading images and
66
+ cancelling highlights.
67
+
68
+ ### Changed
69
+ - Dependencies move to their latest releases: jest 30, marked 18, and the
70
+ latest minor versions of every gem. `sinatra-contrib` is no longer used.
71
+ - The gem now includes its LICENSE, README and CHANGELOG.
72
+
73
+ ## [1.0.3] - 2026-09-20
74
+
75
+ ### Fixed
76
+ - The web UI returned 404 at `http://localhost:4567`, the address the README
77
+ and `agent-chat-web --help` both give. Sinatra serves the public folder but
78
+ does not map `/` to its index, so only `/index.html` worked.
79
+
80
+ ### Changed
81
+ - `puma` moves from 7.x to 8.x.
82
+ - `required_ruby_version` is now `>= 3.2`. The stated floor of 3.0 was never
83
+ reachable, because sqlite3 requires 3.2.
84
+ - Publishing requires multi-factor auth, and the gemspec carries the homepage,
85
+ bug tracker and documentation links it was missing.
86
+
87
+ ## [1.0.2] - 2026-02-20
88
+
89
+ ### Fixed
90
+ - SQLite3::BusyException when multiple agents access the same room concurrently
91
+ - Enable WAL journal mode and busy timeout for reliable multi-process database access
92
+
93
+ ## [1.0.1] - 2026-02-12
94
+
95
+ ### Added
96
+ - `--version` / `-v` flag for both `agent-chat` and `agent-chat-web`
97
+ - `--help` / `-h` flag for `agent-chat-web`
98
+ - GitHub metadata in gemspec
99
+ - Bundler gem_tasks for `rake release`
100
+
101
+ ### Fixed
102
+ - Message duplication in web UI when loading rooms
103
+ - Message duplication in web UI when polling returns already-loaded messages
104
+ - Bash history expansion issue in help text example (`echo "Hello!"` → `echo 'Hello!'`)
105
+ - Graceful handling of missing `xdg-open` on Linux when opening browser
106
+
107
+ ## [1.0.0] - 2026-02-12
108
+
109
+ ### Added
110
+ - CLI tool (`agent-chat`) with send, receive, and stream commands for inter-agent messaging
111
+ - Web UI (`agent-chat-web`) with dark-themed chat interface for browsing and posting messages
112
+ - Room-based SQLite persistence with each room maintaining its own database
113
+ - Consumer read position tracking to show only new messages for each consumer
114
+ - Markdown rendering support in web UI messages
115
+ - Optimistic message posting in web UI with instant feedback
116
+ - Auto-scroll functionality with scroll position preservation
117
+ - Keyboard shortcuts: Enter to send messages, Shift+Enter for newlines
118
+ - Room discovery from filesystem with automatic listing
119
+ - Cross-platform browser opening support (macOS, Linux, Windows)
120
+ - Comprehensive test suite: 34 unit tests, 13 acceptance tests, 22 frontend tests
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Erik Thyge Madsen
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,196 @@
1
+ # agent-chat
2
+
3
+ A chat messaging tool for inter-agent communication, backed by SQLite. Designed for AI agents (or humans) that need a simple shared message queue with room-based conversations.
4
+
5
+ Includes a CLI (`agent-chat`) and a web UI (`agent-chat-web`).
6
+
7
+ ## Installation
8
+
9
+ ```
10
+ gem install agent-chat
11
+ ```
12
+
13
+ Or add to your Gemfile:
14
+
15
+ ```ruby
16
+ gem "agent-chat"
17
+ ```
18
+
19
+ Requires Ruby >= 3.3.
20
+
21
+ ## CLI Usage
22
+
23
+ ```
24
+ agent-chat <command> [options]
25
+ ```
26
+
27
+ ### Commands
28
+
29
+ **send** reads the message from stdin and prints the id it was given:
30
+
31
+ ```bash
32
+ echo "Hello!" | agent-chat send --room general --author Alice
33
+ # 7xKqR2m
34
+ ```
35
+
36
+ Answer one or more earlier messages with `--reply-to`:
37
+
38
+ ```bash
39
+ echo "Agreed" | agent-chat send --room general --author Bob --reply-to 7xKqR2m,3fGhJ9k
40
+ ```
41
+
42
+ **receive** prints the messages this consumer has not seen yet, then exits:
43
+
44
+ ```bash
45
+ agent-chat receive --room general --consumer Bob
46
+ ```
47
+
48
+ **stream** does the same and keeps printing new messages until Ctrl-C:
49
+
50
+ ```bash
51
+ agent-chat stream --room general --consumer Bob
52
+ ```
53
+
54
+ **show** prints messages by id, for example the ones a reply answers:
55
+
56
+ ```bash
57
+ agent-chat show --room general 7xKqR2m 3fGhJ9k
58
+ ```
59
+
60
+ ### Options
61
+
62
+ | Option | Description |
63
+ |--------|-------------|
64
+ | `--room <name>` | Chat room name (every command) |
65
+ | `--author <name>` | Who the message is from (`send`) |
66
+ | `--consumer <name>` | Reader name with its own read position (`receive`, `stream`) |
67
+ | `--reply-to <id,...>` | Ids this message answers (`send`); repeat or comma-separate |
68
+ | `--all` | Whole history instead of unread messages; moves no read position (`receive`, `stream`) |
69
+ | `--json` | Structured output, one JSON object per line |
70
+ | `-h, --help` | Show help |
71
+ | `-v, --version` | Show the version |
72
+
73
+ A misspelt flag or command one edit away from exactly one known name is read as that name, with a warning. Anything less certain is refused.
74
+
75
+ ### Text output
76
+
77
+ ```
78
+ <<< Alice | 2026-11-22 14:30:00 | 7xKqR2m >>>
79
+ Shall we ship?
80
+
81
+
82
+
83
+ <<< Bob | 2026-11-22 14:31:12 | 3fGhJ9k | re: 7xKqR2m >>>
84
+ Yes
85
+ ```
86
+
87
+ Times are local. Notes, warnings and errors go to stderr.
88
+
89
+ ### JSON output
90
+
91
+ With `--json`, `receive`, `stream` and `show` print one line per message:
92
+
93
+ ```json
94
+ {"id":"3fGhJ9k","author":"Bob","timestamp":"2026-11-22T13:31:12Z","content":"Yes","reply_to":["7xKqR2m"]}
95
+ ```
96
+
97
+ `receive` prints nothing when there is nothing new. `send` prints only what the sender does not already know:
98
+
99
+ ```json
100
+ {"status":"accepted","assigned_id":"3fGhJ9k"}
101
+ ```
102
+
103
+ It adds `"room_created":true` when the message created the room. A refused request prints an error object on stdout:
104
+
105
+ ```json
106
+ {"status":"rejected","error":{"code":"unknown_reply_to","message":"No message with id zzzzzzz in room general","ids":["zzzzzzz"]}}
107
+ ```
108
+
109
+ Notes and warnings from `receive`, `stream` and `show` go to stderr as `{"info":{...}}` or `{"warning":{...}}` lines, so stdout stays a clean stream of messages. For `send` and for refused requests they appear in a `"warnings"` list.
110
+
111
+ Exit status is 0 on success, 1 when a request is refused and 2 when the command line cannot be read.
112
+
113
+ ## Web UI
114
+
115
+ Launch the web interface:
116
+
117
+ ```bash
118
+ agent-chat-web
119
+ ```
120
+
121
+ This starts a Sinatra server on `http://localhost:4567` and opens it in your browser. Each message shows its id and links to the messages it answers; click a link to jump to that message. Reply collects one or more messages to answer with your next post. Add `?consumer=<name>` to the address to read and post under a name.
122
+
123
+ ### API Endpoints
124
+
125
+ | Method | Path | Description |
126
+ |--------|------|-------------|
127
+ | GET | `/api/rooms` | List all rooms |
128
+ | GET | `/api/rooms/:room/messages` | All messages in a room; with `?consumer=NAME` also marks them read |
129
+ | GET | `/api/rooms/:room/messages/new?consumer=NAME` | Messages the consumer has not read |
130
+ | POST | `/api/rooms/:room/messages` | Send a message: `application/json` body with `author`, `content` and optional `reply_to` |
131
+
132
+ Messages have the same fields as the CLI's JSON lines. A POST answers 201 with `{"status":"accepted","assigned_id":...}`. Problems come back as the same error object as the CLI, with status 400, 415 for a body that is not JSON, or 422 for an unknown message id.
133
+
134
+ ## How It Works
135
+
136
+ Each room is a SQLite database in your system's temp directory:
137
+
138
+ ```
139
+ $TMPDIR/agent-chat/rooms/<room-name>/room.db
140
+ ```
141
+
142
+ - **Rooms** are independent chat channels, each with its own database file. Reading or sending to a room that does not exist creates it, and the command says so.
143
+ - **Consumers** track read positions independently. `receive` only returns messages the consumer has not seen before.
144
+ - **No server required** for CLI usage. Several processes can read and write the same room at once.
145
+ - Messages persist across restarts until the temp directory is cleaned up.
146
+ - A room created by a different version of agent-chat is moved to `$TMPDIR/agent-chat/backups/<UTC time>/<room>/` and started over, with a warning that names the backup.
147
+
148
+ ## Multi-Agent Example
149
+
150
+ Launch three Claude agents that chat with each other:
151
+
152
+ ```bash
153
+ USAGE='Send: echo "message" | agent-chat send --json --room general --author NAME [--reply-to ID,...]
154
+ Receive: agent-chat receive --json --room general --consumer NAME
155
+ Look up a message you were answered about: agent-chat show --json --room general ID'
156
+
157
+ claude --dangerously-skip-permissions -p "$USAGE
158
+ You are Alice, a friendly agent. Send a greeting, then poll for responses
159
+ every few seconds and reply to specific messages. Continue for 2-3 exchanges." &
160
+
161
+ claude --dangerously-skip-permissions -p "$USAGE
162
+ You are Bob, a curious agent who asks questions. Poll for messages frequently
163
+ and reply to the messages you are answering. Continue for 2-3 exchanges." &
164
+
165
+ claude --dangerously-skip-permissions -p "$USAGE
166
+ You are Charlie, a witty agent. Poll for messages frequently and reply with
167
+ witty comments. Continue for 2-3 exchanges." &
168
+ ```
169
+
170
+ Watch the conversation:
171
+
172
+ ```bash
173
+ agent-chat stream --room general --all
174
+ ```
175
+
176
+ ## Tips
177
+
178
+ - All participants share the same room name. That is all they need.
179
+ - Use `--json` from scripts and agents. Text output is for people.
180
+ - Use `stream` for continuous monitoring and `receive` for one-shot polling.
181
+ - Each consumer name must be unique. Two readers sharing a consumer name split the messages between them.
182
+ - Sandboxed subagents (e.g. Claude Code's Task tool) cannot use external executables. Launch full Claude sessions instead.
183
+
184
+ ## Development
185
+
186
+ The frontend tests need Node.js.
187
+
188
+ ```bash
189
+ bundle install
190
+ npm install
191
+ bundle exec rake
192
+ ```
193
+
194
+ ## License
195
+
196
+ MIT
data/config.ru CHANGED
@@ -1,8 +1,3 @@
1
- require 'agent_chat'
2
- require 'tmpdir'
3
-
4
- tmpdir = Dir.tmpdir
5
- AgentChat::Web::App.set :room_discovery, AgentChat::Web::RoomDiscoveryService.new(tmpdir: tmpdir)
6
- AgentChat::Web::App.set :service_factory, AgentChat::Web::ServiceFactory.new(tmpdir: tmpdir)
1
+ require 'agent_chat/web/app'
7
2
 
8
3
  run AgentChat::Web::App
data/exe/agent-chat CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env ruby
2
- require 'agent_chat'
2
+ require 'agent_chat/cli/runner'
3
3
 
4
- AgentChat::CLIAdapter.setup($stdin, $stdout, ARGV).run(ARGV)
4
+ terminal = AgentChat::CLI::Terminal.new(stdin: $stdin, stdout: $stdout, stderr: $stderr)
5
+ exit AgentChat::CLI::Runner.new(terminal).run(ARGV)
data/exe/agent-chat-web CHANGED
@@ -1,6 +1,5 @@
1
1
  #!/usr/bin/env ruby
2
- require 'agent_chat'
3
- require 'tmpdir'
2
+ require 'agent_chat/version'
4
3
 
5
4
  if ARGV.include?('--version') || ARGV.include?('-v')
6
5
  puts "agent-chat-web #{AgentChat::VERSION}"
@@ -9,7 +8,7 @@ end
9
8
 
10
9
  if ARGV.include?('--help') || ARGV.include?('-h')
11
10
  puts <<~HELP
12
- agent-chat-web - Web UI for agent-chat
11
+ agent-chat-web starts the web UI for agent-chat.
13
12
 
14
13
  Usage:
15
14
  agent-chat-web [options]
@@ -23,13 +22,11 @@ if ARGV.include?('--help') || ARGV.include?('-h')
23
22
  exit
24
23
  end
25
24
 
26
- tmpdir = Dir.tmpdir
27
- AgentChat::Web::App.set :room_discovery, AgentChat::Web::RoomDiscoveryService.new(tmpdir: tmpdir)
28
- AgentChat::Web::App.set :service_factory, AgentChat::Web::ServiceFactory.new(tmpdir: tmpdir)
25
+ require 'agent_chat/web/app'
29
26
 
30
27
  Thread.new do
31
28
  sleep 1
32
- url = 'http://localhost:4567/index.html'
29
+ url = 'http://localhost:4567'
33
30
  case RUBY_PLATFORM
34
31
  when /darwin/
35
32
  system('open', url)
@@ -0,0 +1,24 @@
1
+ require_relative 'missing_ids'
2
+ require_relative '../message'
3
+
4
+ module AgentChat
5
+ class Chat
6
+ Draft = Data.define(:author, :content, :reply_to) do
7
+ def self.of(author:, content:, reply_to:)
8
+ new(author:, content:, reply_to: reply_to.uniq)
9
+ end
10
+
11
+ def problems(existing_ids, room)
12
+ return [Problem.new(:missing_author, 'A message needs an author')] if author.to_s.strip.empty?
13
+ return [Problem.new(:empty_content, 'A message needs content')] if content.to_s.strip.empty?
14
+
15
+ unknown = reply_to.reject { |id| existing_ids.include?(id) }
16
+ unknown.empty? ? [] : [MissingIds.problem(:unknown_reply_to, unknown, room)]
17
+ end
18
+
19
+ def to_message(id:, timestamp:)
20
+ Message.new(id:, author:, content:, timestamp:, reply_to:)
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,34 @@
1
+ require_relative '../chat'
2
+ require_relative '../global_id'
3
+ require_relative '../room/name'
4
+ require_relative '../room/opener'
5
+
6
+ module AgentChat
7
+ class Chat
8
+ Visit = Data.define(:chat, :arrival, :similar_rooms)
9
+
10
+ class Entrance
11
+ def initialize(root, clock: -> { Time.now })
12
+ @directory = Room::Directory.new(root)
13
+ @clock = clock
14
+ end
15
+
16
+ def enter(room)
17
+ problems = Room::Name.problems_with(room)
18
+ return Rejected.new(problems.first) unless problems.empty?
19
+
20
+ db, arrival = Room::Opener.new(@directory.location(room), clock: @clock).open
21
+ chat = Chat.new(store: Room::Store.new(db), room:, clock: @clock, id_source: -> { GlobalId.generate })
22
+ Accepted.new(Visit.new(chat:, arrival:, similar_rooms: similar_rooms(room, arrival)))
23
+ end
24
+
25
+ private
26
+
27
+ def similar_rooms(room, arrival)
28
+ return [] unless arrival.kind == :created
29
+
30
+ @directory.names_near(room)
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,12 @@
1
+ require_relative '../problem'
2
+
3
+ module AgentChat
4
+ class Chat
5
+ module MissingIds
6
+ def self.problem(code, ids, room)
7
+ noun = ids.one? ? 'message with id' : 'messages with ids'
8
+ Problem.new(code, "No #{noun} #{ids.join(', ')} in room #{room}", ids:)
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,56 @@
1
+ require_relative 'outcome'
2
+ require_relative 'room/store'
3
+ require_relative 'chat/draft'
4
+ require_relative 'chat/missing_ids'
5
+
6
+ module AgentChat
7
+ class Chat
8
+ def initialize(store:, room:, clock:, id_source:)
9
+ @store = store
10
+ @room = room
11
+ @clock = clock
12
+ @id_source = id_source
13
+ end
14
+
15
+ def post(author:, content:, reply_to:)
16
+ draft = Draft.of(author:, content:, reply_to:)
17
+ existing = @store.existing_ids(draft.reply_to)
18
+ problems = draft.problems(existing, @room)
19
+ return Rejected.new(problems.first) unless problems.empty?
20
+
21
+ Accepted.new(save(draft))
22
+ end
23
+
24
+ def unread(consumer)
25
+ messages = @store.messages_after(@store.read_position(consumer))
26
+ mark_read(consumer, through: messages.last.id) unless messages.empty?
27
+ messages
28
+ end
29
+
30
+ def mark_read(consumer, through:)
31
+ @store.move_read_position(consumer, to: through)
32
+ end
33
+
34
+ def history = @store.messages_after(nil)
35
+ def history_after(id) = @store.messages_after(id)
36
+
37
+ def find(ids)
38
+ wanted = ids.uniq
39
+ found = @store.messages_with_ids(wanted).to_h { |message| [message.id, message] }
40
+ unknown = wanted.reject { |id| found.key?(id) }
41
+ return Rejected.new(MissingIds.problem(:unknown_id, unknown, @room)) unless unknown.empty?
42
+
43
+ Accepted.new(found.values_at(*wanted))
44
+ end
45
+
46
+ private
47
+
48
+ def save(draft)
49
+ message = draft.to_message(id: @id_source.call, timestamp: @clock.call)
50
+ @store.insert(message)
51
+ message.id
52
+ rescue Room::IdTaken
53
+ retry
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,29 @@
1
+ require_relative 'notice'
2
+
3
+ module AgentChat
4
+ module CLI
5
+ module ArrivalNotices
6
+ def self.for(visit, room)
7
+ case visit.arrival.kind
8
+ when :created then [Notice.new(:info, created(room, visit.similar_rooms))]
9
+ when :reset then [Notice.new(:warning, reset(room, visit.arrival.backup_path))]
10
+ else []
11
+ end
12
+ end
13
+
14
+ def self.created(room, similar_rooms)
15
+ message = "Room #{room} did not exist; created it. You are the first here."
16
+ return Problem.new(:room_created, message) if similar_rooms.empty?
17
+
18
+ rooms = similar_rooms.map { |name| "a room named #{name}" }.join(' and ')
19
+ verb = similar_rooms.one? ? 'exists' : 'exist'
20
+ Problem.new(:room_created, "#{message} Note that #{rooms} #{verb}.", similar_rooms:)
21
+ end
22
+
23
+ def self.reset(room, backup_path)
24
+ Problem.new(:room_reset, "Room #{room} was made by an older version of agent-chat. " \
25
+ "Moved it to #{backup_path} and started the room over.", backup_path:)
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,37 @@
1
+ require_relative 'tokenizer'
2
+ require_relative 'request_builder'
3
+
4
+ module AgentChat
5
+ module CLI
6
+ class CommandLine
7
+ def initialize(args)
8
+ @args = args
9
+ end
10
+
11
+ def parse
12
+ return Parse.accepted(special(:help)) if @args.empty? || @args.intersect?(Vocabulary::HELP)
13
+ return Parse.accepted(special(:version)) if @args.intersect?(Vocabulary::VERSION)
14
+
15
+ Tokenizer.new(@args).tokenize.and_then do |tokens|
16
+ resolve_command(tokens.positionals.first).and_then { |command| RequestBuilder.new(command, tokens).build }
17
+ end
18
+ end
19
+
20
+ def json_requested? = @args.any? { |arg| Vocabulary.flag_name(arg.split('=').first) == '--json' }
21
+
22
+ private
23
+
24
+ def special(command) = Request.special(command, json: json_requested?)
25
+
26
+ def resolve_command(given)
27
+ return Parse.rejected(Wording.missing_command) if given.nil?
28
+
29
+ match = Lookup.find(given.downcase, Vocabulary.command_names)
30
+ return Parse.rejected(Wording.unknown_command(given, match.suggestions)) if match.is_a?(Lookup::Unknown)
31
+
32
+ notices = given == match.word ? [] : [Wording.interpreted(:interpreted_command, given, match.word)]
33
+ Parse.accepted(match.word, notices)
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,51 @@
1
+ module AgentChat
2
+ module CLI
3
+ module Commands
4
+ class Send
5
+ def initialize(chat:, output:, stdin:)
6
+ @chat = chat
7
+ @output = output
8
+ @stdin = stdin
9
+ end
10
+
11
+ def run(request, notices)
12
+ content = @stdin.read.chomp
13
+ outcome = @chat.post(author: request.author, content:, reply_to: request.reply_to)
14
+ return Runner::REFUSED.tap { @output.rejected(outcome.problem, notices) } if outcome.is_a?(Rejected)
15
+
16
+ @output.posted(outcome.value, notices)
17
+ Runner::OK
18
+ end
19
+ end
20
+
21
+ class Receive
22
+ def initialize(chat:, output:)
23
+ @chat = chat
24
+ @output = output
25
+ end
26
+
27
+ def run(request, notices)
28
+ @output.notices(notices)
29
+ @output.messages(request.all ? @chat.history : @chat.unread(request.consumer))
30
+ Runner::OK
31
+ end
32
+ end
33
+
34
+ class Show
35
+ def initialize(chat:, output:)
36
+ @chat = chat
37
+ @output = output
38
+ end
39
+
40
+ def run(request, notices)
41
+ @output.notices(notices)
42
+ outcome = @chat.find(request.ids)
43
+ return Runner::REFUSED.tap { @output.rejected(outcome.problem, []) } if outcome.is_a?(Rejected)
44
+
45
+ @output.messages(outcome.value)
46
+ Runner::OK
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end