tensaku 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/CHANGELOG.md +144 -2
- data/README.md +15 -11
- data/app/assets/tensaku.js +187 -331
- data/exe/tensaku +5 -0
- data/lib/generators/tensaku/install_generator.rb +98 -46
- data/lib/tensaku/agents.rb +143 -0
- data/lib/tensaku/build.rb +32 -0
- data/lib/tensaku/cli.rb +155 -0
- data/lib/tensaku/doorbell.rb +91 -0
- data/lib/tensaku/endpoints.rb +80 -18
- data/lib/tensaku/file_write.rb +14 -3
- data/lib/tensaku/guard.rb +1 -2
- data/lib/tensaku/mcp.rb +112 -127
- data/lib/tensaku/middleware.rb +1 -1
- data/lib/tensaku/notes/markdown.rb +83 -0
- data/lib/tensaku/notes/target.rb +59 -0
- data/lib/tensaku/notes.rb +248 -254
- data/lib/tensaku/presence.rb +60 -0
- data/lib/tensaku/project.rb +98 -0
- data/lib/tensaku/railtie.rb +16 -1
- data/lib/tensaku/repo.rb +57 -0
- data/lib/tensaku/session/tools.rb +164 -0
- data/lib/tensaku/session.rb +267 -0
- data/lib/tensaku/source/locale.rb +1 -1
- data/lib/tensaku/source/markdown.rb +3 -2
- data/lib/tensaku/source/template.rb +3 -2
- data/lib/tensaku/store.rb +196 -0
- data/lib/tensaku/version.rb +1 -1
- data/lib/tensaku.rb +36 -12
- data/skills/tensaku/SKILL.md +56 -15
- metadata +32 -5
data/lib/tensaku/endpoints.rb
CHANGED
|
@@ -2,14 +2,22 @@ require "json"
|
|
|
2
2
|
require "digest"
|
|
3
3
|
|
|
4
4
|
module Tensaku
|
|
5
|
-
# The JSON endpoints the overlay talks to, plus the overlay script
|
|
6
|
-
#
|
|
5
|
+
# The JSON endpoints the overlay talks to, plus the overlay script. Everything needs a loopback
|
|
6
|
+
# address, and everything except the script needs the boot token. Agents don't come through here:
|
|
7
|
+
# `tensaku mcp` works on the database directly.
|
|
7
8
|
class Endpoints
|
|
8
9
|
ASSET = File.expand_path("../../app/assets/tensaku.js", __dir__)
|
|
9
10
|
|
|
10
11
|
# Edit mode asks about every stamp on the page at once.
|
|
11
12
|
EDITABLE_LIMIT = 5000
|
|
12
13
|
|
|
14
|
+
# An event stream waits on the doorbell, and checks anyway this often: for an agent that stopped
|
|
15
|
+
# checking in, and to write a comment so a closed tab is noticed.
|
|
16
|
+
STREAM_CHECK = 10
|
|
17
|
+
|
|
18
|
+
# /notes/ID and /notes/ID/screenshot.
|
|
19
|
+
NOTE_PATH = %r{\A/notes/([a-z0-9]+)(?:/screenshot)?\z}
|
|
20
|
+
|
|
13
21
|
def self.asset_digest
|
|
14
22
|
Digest::SHA256.file(ASSET).hexdigest[0, 12]
|
|
15
23
|
rescue Errno::ENOENT
|
|
@@ -22,11 +30,6 @@ module Tensaku
|
|
|
22
30
|
|
|
23
31
|
return script(request) if path == "/tensaku.js" && request.get?
|
|
24
32
|
|
|
25
|
-
if path == "/mcp"
|
|
26
|
-
Guard.check_local_client!(request)
|
|
27
|
-
return Mcp.new.call(request)
|
|
28
|
-
end
|
|
29
|
-
|
|
30
33
|
Guard.check_request!(request)
|
|
31
34
|
route(request, path)
|
|
32
35
|
rescue Forbidden => error
|
|
@@ -47,6 +50,7 @@ module Tensaku
|
|
|
47
50
|
|
|
48
51
|
def route(request, path)
|
|
49
52
|
params = request.get? ? request.GET : body(request)
|
|
53
|
+
note_id = path[NOTE_PATH, 1]
|
|
50
54
|
|
|
51
55
|
case [ request.request_method, path ]
|
|
52
56
|
in [ "GET", "/source" ]
|
|
@@ -76,31 +80,89 @@ module Tensaku
|
|
|
76
80
|
in [ "POST", "/markdown" ]
|
|
77
81
|
written(:markdown) { Source::Markdown.new(params["range"]).edit(original: params["original"], text: params["text"], tag: params["tag"]) }
|
|
78
82
|
in [ "GET", "/notes" ]
|
|
79
|
-
|
|
80
|
-
|
|
83
|
+
visited(request)
|
|
84
|
+
# restart: Tensaku's code changed since this server started, so it answers with the old code
|
|
85
|
+
# while the page runs the new overlay script.
|
|
86
|
+
# archived=1 lists the archive instead, for the notes panel's Archive tab.
|
|
87
|
+
listed = Notes.list(url: params["url"].presence, status: ("archived" if params["archived"] == "1"))
|
|
88
|
+
# changed_at: the last time an agent said something on a note in this app, so the page fetches
|
|
89
|
+
# itself again to show its change, whatever page the note was on.
|
|
90
|
+
json(notes: listed, open: Notes.active_count, agents: Agents.list, restart: Build.stale?, changed_at: Notes.last_agent_message_at)
|
|
91
|
+
in [ "GET", "/events" ]
|
|
92
|
+
events(request)
|
|
81
93
|
in [ "GET", "/notes.md" ]
|
|
82
|
-
notes =
|
|
83
|
-
markdown = params["format"] == "short" ? Notes.
|
|
94
|
+
notes = Notes.list(url: params["url"].presence, status: Notes::ACTIVE)
|
|
95
|
+
markdown = params["format"] == "short" ? Notes::Markdown.short(notes) : Notes::Markdown.list(notes)
|
|
84
96
|
[ 200, { "content-type" => "text/markdown; charset=utf-8" }, [ markdown ] ]
|
|
85
97
|
in [ "POST", "/notes" ]
|
|
86
98
|
json(Notes.create(params), 201)
|
|
87
|
-
in [ "
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
99
|
+
in [ "PUT", %r{\A/notes/[a-z0-9]+/screenshot\z} ]
|
|
100
|
+
json(Notes.attach_screenshot(note_id, params["png"]))
|
|
101
|
+
in [ "GET", %r{\A/notes/[a-z0-9]+/screenshot\z} ]
|
|
102
|
+
shot = Notes.screenshot(note_id) or raise Notes::NotFound, "That note has no screenshot"
|
|
103
|
+
[ 200, { "content-type" => "image/png", "cache-control" => "no-store" }, [ shot["png"] ] ]
|
|
104
|
+
in [ "PATCH", %r{\A/notes/[a-z0-9]+\z} ]
|
|
105
|
+
# An edit or a message is for the agent: the note is sent again. A status change alone (done,
|
|
106
|
+
# reopened, or undoing either) isn't.
|
|
107
|
+
changed = params["message"].present? || params["comment"].present?
|
|
108
|
+
json(Notes.update(note_id, status: params["status"], comment: params["comment"],
|
|
109
|
+
message: params["message"], from: "you", send: changed && params["status"] == "open", to: params["to"]))
|
|
110
|
+
in [ "POST", "/notes/archive" ]
|
|
111
|
+
json(archived: Notes.archive!(params["ids"]))
|
|
112
|
+
in [ "DELETE", %r{\A/notes/[a-z0-9]+\z} ]
|
|
113
|
+
Notes.delete(note_id)
|
|
93
114
|
json({ deleted: true })
|
|
94
115
|
in [ "GET", "/editor" ]
|
|
95
116
|
json(url: editor_url(params["file"], params["line"]))
|
|
96
117
|
in [ "POST", "/selection" ]
|
|
97
|
-
|
|
118
|
+
Project.select!(params.to_h.slice("url", "targets", "text"), tab: params["tab"])
|
|
98
119
|
json({ ok: true })
|
|
99
120
|
else
|
|
100
121
|
json({ error: "Not found" }, 404)
|
|
101
122
|
end
|
|
102
123
|
end
|
|
103
124
|
|
|
125
|
+
# Server-sent events: one "changed" event whenever the notes or the agents change (Project.version),
|
|
126
|
+
# and one right away, so the page loads the notes when told instead of asking every few seconds.
|
|
127
|
+
# The stream sleeps on the doorbell until a write rings it.
|
|
128
|
+
# The connection is taken over from the web server (Rack hijack) and served from a thread of its
|
|
129
|
+
# own, so an open tab doesn't hold one of the server's threads. A server without hijack answers
|
|
130
|
+
# 501, and the page polls instead.
|
|
131
|
+
def events(request)
|
|
132
|
+
hijack = request.env["rack.hijack"]
|
|
133
|
+
return json({ error: "This web server can't stream events" }, 501) unless hijack
|
|
134
|
+
|
|
135
|
+
visited(request)
|
|
136
|
+
io = hijack.call
|
|
137
|
+
root = Tensaku.root
|
|
138
|
+
Thread.new { Tensaku.with_root(root) { stream(io) } }
|
|
139
|
+
[ -1, {}, [] ]
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
def stream(io)
|
|
143
|
+
Doorbell.listen(Tensaku.root) do |doorbell|
|
|
144
|
+
io.write("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncache-control: no-store\r\nconnection: close\r\n\r\n")
|
|
145
|
+
last = nil
|
|
146
|
+
loop do
|
|
147
|
+
version = Project.version
|
|
148
|
+
io.write(version == last ? ": ping\n\n" : "data: changed\n\n")
|
|
149
|
+
io.flush
|
|
150
|
+
last = version
|
|
151
|
+
doorbell.wait(STREAM_CHECK)
|
|
152
|
+
end
|
|
153
|
+
end
|
|
154
|
+
rescue IOError, SystemCallError
|
|
155
|
+
nil # the tab closed
|
|
156
|
+
ensure
|
|
157
|
+
io.close unless io.closed?
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
# The page asks for its notes: archive the old ones, and keep the URL agents' links start with.
|
|
161
|
+
def visited(request)
|
|
162
|
+
Notes.prune!
|
|
163
|
+
Project.base_url = request.base_url
|
|
164
|
+
end
|
|
165
|
+
|
|
104
166
|
# A link that opens the file in the editor named by RAILS_EDITOR or EDITOR, through Rails' own
|
|
105
167
|
# list of editors, or nil when none is set.
|
|
106
168
|
def editor_url(file, line)
|
data/lib/tensaku/file_write.rb
CHANGED
|
@@ -2,13 +2,13 @@ module Tensaku
|
|
|
2
2
|
module FileWrite
|
|
3
3
|
module_function
|
|
4
4
|
|
|
5
|
-
# Runs the block holding one lock shared by every thread and every
|
|
6
|
-
# can't both read a file, check it and then overwrite each other's change. Writers re-read the file
|
|
5
|
+
# Runs the block holding one lock shared by every thread and every process (the dev server and
|
|
6
|
+
# `tensaku mcp`), so two saves can't both read a file, check it and then overwrite each other's change. Writers re-read the file
|
|
7
7
|
# inside the block. Nested calls in the same thread don't wait on themselves.
|
|
8
8
|
def locked
|
|
9
9
|
return yield if Thread.current[:tensaku_write_lock]
|
|
10
10
|
|
|
11
|
-
path =
|
|
11
|
+
path = Tensaku.root.join("tmp/tensaku/write.lock")
|
|
12
12
|
path.dirname.mkpath
|
|
13
13
|
File.open(path, File::RDWR | File::CREAT, 0o644) do |file|
|
|
14
14
|
file.flock(File::LOCK_EX)
|
|
@@ -48,5 +48,16 @@ module Tensaku
|
|
|
48
48
|
end
|
|
49
49
|
result.force_encoding(source.encoding)
|
|
50
50
|
end
|
|
51
|
+
|
|
52
|
+
# The lines a write changed, for the overlay's save message: the first line's number, then the old
|
|
53
|
+
# and new lines between what the two versions share at each end.
|
|
54
|
+
def diff(before, after)
|
|
55
|
+
was, now = [ before, after ].map { it.dup.force_encoding(Encoding::UTF_8).scrub.lines(chomp: true) }
|
|
56
|
+
prefix = 0
|
|
57
|
+
prefix += 1 while prefix < was.size && prefix < now.size && was[prefix] == now[prefix]
|
|
58
|
+
suffix = 0
|
|
59
|
+
suffix += 1 while suffix < was.size - prefix && suffix < now.size - prefix && was[-1 - suffix] == now[-1 - suffix]
|
|
60
|
+
{ line: prefix + 1, removed: was[prefix...(was.size - suffix)], added: now[prefix...(now.size - suffix)] }
|
|
61
|
+
end
|
|
51
62
|
end
|
|
52
63
|
end
|
data/lib/tensaku/guard.rb
CHANGED
|
@@ -32,8 +32,7 @@ module Tensaku
|
|
|
32
32
|
raise Forbidden, "Missing or wrong Tensaku token. Reload the page." unless secure_compare(token, Tensaku.token)
|
|
33
33
|
end
|
|
34
34
|
|
|
35
|
-
#
|
|
36
|
-
# check alone. Every other endpoint adds the token on top.
|
|
35
|
+
# Every endpoint but the script adds the token on top of this.
|
|
37
36
|
def check_local_client!(request)
|
|
38
37
|
raise Forbidden, "Tensaku only answers requests from this machine" unless loopback?(request)
|
|
39
38
|
|
data/lib/tensaku/mcp.rb
CHANGED
|
@@ -1,83 +1,79 @@
|
|
|
1
1
|
require "json"
|
|
2
2
|
|
|
3
3
|
module Tensaku
|
|
4
|
-
#
|
|
5
|
-
#
|
|
6
|
-
#
|
|
4
|
+
# The MCP server an agent starts with `tensaku mcp`: newline-delimited JSON-RPC over stdin and stdout,
|
|
5
|
+
# in front of one Session. The dev server doesn't have to be running and no port is configured.
|
|
6
|
+
#
|
|
7
|
+
# Claude Code channels: the server declares the experimental claude/channel capability, which lets it
|
|
8
|
+
# push a message into a Claude Code session started with
|
|
9
|
+
# `claude --dangerously-load-development-channels server:tensaku`; the message starts a turn as if the
|
|
10
|
+
# person had typed it. A session without the flag drops these messages without an error, so the
|
|
11
|
+
# server first sends a hello with a code and the session only treats the channel as working once
|
|
12
|
+
# Claude calls channel_ready with that code (see Session).
|
|
7
13
|
class Mcp
|
|
8
14
|
PROTOCOL_VERSIONS = %w[2025-11-25 2025-06-18 2025-03-26 2024-11-05].freeze
|
|
9
|
-
MAX_WATCH = 300
|
|
10
15
|
|
|
11
|
-
|
|
12
|
-
{
|
|
13
|
-
name: "list_notes",
|
|
14
|
-
description: "List Tensaku notes left on pages of this Rails app. Each note has a comment and targets with the exact file and line range that rendered the element. Defaults to notes that need work (open, working and question).",
|
|
15
|
-
inputSchema: {
|
|
16
|
-
type: "object",
|
|
17
|
-
properties: {
|
|
18
|
-
status: { type: "string", enum: %w[open working question resolved active all], description: "active (default) means open, working or question." },
|
|
19
|
-
url: { type: "string", description: "Only notes left on this path, for example /about." }
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
},
|
|
23
|
-
{
|
|
24
|
-
name: "get_note",
|
|
25
|
-
description: "Get one Tensaku note by id.",
|
|
26
|
-
inputSchema: { type: "object", properties: { id: { type: "string" } }, required: [ "id" ] }
|
|
27
|
-
},
|
|
28
|
-
{
|
|
29
|
-
name: "start_note",
|
|
30
|
-
description: "Mark a note as being worked on before you make the change. The pin on the page shows that an agent has picked it up. Resolve it with resolve_note when done.",
|
|
31
|
-
inputSchema: { type: "object", properties: { id: { type: "string" } }, required: [ "id" ] }
|
|
32
|
-
},
|
|
33
|
-
{
|
|
34
|
-
name: "resolve_note",
|
|
35
|
-
description: "Mark a note resolved after making the change. The reply is shown on the page next to a green pin, so say briefly what changed and where (for example: changed the heading in app/views/pages/_hero.html.erb:4).",
|
|
36
|
-
inputSchema: { type: "object", properties: { id: { type: "string" }, reply: { type: "string" } }, required: %w[id reply] }
|
|
37
|
-
},
|
|
38
|
-
{
|
|
39
|
-
name: "ask_question",
|
|
40
|
-
description: "Ask the person who wrote a note for clarification instead of guessing. The question shows on the page; the note's status becomes question until they answer by editing the note.",
|
|
41
|
-
inputSchema: { type: "object", properties: { id: { type: "string" }, question: { type: "string" } }, required: %w[id question] }
|
|
42
|
-
},
|
|
43
|
-
{
|
|
44
|
-
name: "reply_to_note",
|
|
45
|
-
description: "Add a message to a note's thread without changing its status, for example to say what you found or what you will do. It shows on the page under the note.",
|
|
46
|
-
inputSchema: { type: "object", properties: { id: { type: "string" }, message: { type: "string" } }, required: %w[id message] }
|
|
47
|
-
},
|
|
48
|
-
{
|
|
49
|
-
name: "watch_notes",
|
|
50
|
-
description: "Wait for new or changed open notes, so you can work through notes as they are added. Returns as soon as there are any, or empty after the timeout. Pass the checked_at value of the previous call as since so nothing is missed.",
|
|
51
|
-
inputSchema: {
|
|
52
|
-
type: "object",
|
|
53
|
-
properties: {
|
|
54
|
-
since: { type: "string", description: "ISO 8601 time. Defaults to now." },
|
|
55
|
-
timeout_seconds: { type: "integer", minimum: 1, maximum: MAX_WATCH, description: "Defaults to 60." }
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
},
|
|
59
|
-
{
|
|
60
|
-
name: "current_selection",
|
|
61
|
-
description: "What the person last selected in the Tensaku overlay (elements with file and line), for questions like 'what is this?'.",
|
|
62
|
-
inputSchema: { type: "object", properties: {} }
|
|
63
|
-
}
|
|
64
|
-
].freeze
|
|
16
|
+
CHANNEL_INSTRUCTIONS = " This server may also be a Claude Code channel. Its events arrive as <channel source=\"tensaku\"> messages. The first one asks you to call channel_ready with a code: do that, then tell the person in one line that Tensaku notes now arrive in this chat. Each later event holds notes the person saved on the page, already yours: work through them like notes from watch_notes. There's no need to call watch_notes while the channel works."
|
|
65
17
|
|
|
66
|
-
|
|
67
|
-
# the same.
|
|
68
|
-
def call(request)
|
|
69
|
-
return [ 405, { "allow" => "POST" }, [ "" ] ] unless request.post?
|
|
18
|
+
INSTRUCTIONS = "Tensaku notes are comments a person left on pages of this Rails app, each with the file and line that rendered the element. Work through open notes one at a time: start_note, make the change, then resolve_note with a one-line reply before the next note, so the page shows progress as it happens. Ask a question when a note is unclear, and decline_note when the change shouldn't be made. When the person asks you to watch or listen for notes, call watch_notes in a loop, and tell them the session name its first answer gives you (such as amber-fox), which the page shows next to your name. A note belongs to the session the person assigned it to, was handed it or started it: call start_note before you change anything for a note, and leave notes another session owns. A note with a screenshot says so; get_screenshot returns it. Once you have called watch_notes, notes sent while you work come with the answer of whichever Tensaku tool you call next, already yours: work through them, and call watch_notes again only when you have nothing else to do."
|
|
70
19
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
headers = @new_session ? { "mcp-session-id" => @new_session } : {}
|
|
75
|
-
return [ 202, headers, [ "" ] ] if responses.empty?
|
|
20
|
+
# Claude Code registers its channel listener a moment after initialization, and drops what comes
|
|
21
|
+
# before it (seen in its debug log), so the hello waits, and is sent once more until answered.
|
|
22
|
+
HELLO_AFTER = [ 1.5, 6 ].freeze
|
|
76
23
|
|
|
77
|
-
|
|
78
|
-
|
|
24
|
+
attr_reader :session
|
|
25
|
+
|
|
26
|
+
# apps are the root directories of the Rails apps to serve.
|
|
27
|
+
def initialize(apps, output: $stdout)
|
|
28
|
+
@output = output
|
|
29
|
+
@session = Session.new(apps, push: method(:push))
|
|
30
|
+
@lock = Mutex.new
|
|
31
|
+
@calls = {}
|
|
32
|
+
@claude = false
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Reads requests until stdin closes. Tool calls run in threads of their own, so a waiting
|
|
36
|
+
# watch_notes doesn't hold up other requests and can be cancelled.
|
|
37
|
+
def run(input = $stdin)
|
|
38
|
+
heartbeat = session.heartbeat
|
|
39
|
+
input.each_line do |line|
|
|
40
|
+
next if line.strip.empty?
|
|
41
|
+
|
|
42
|
+
handle(line)
|
|
43
|
+
end
|
|
44
|
+
ensure
|
|
45
|
+
heartbeat&.kill
|
|
46
|
+
close
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# One line of JSON-RPC: a request, a notification or a batch.
|
|
50
|
+
def handle(line)
|
|
51
|
+
message = JSON.parse(line)
|
|
52
|
+
if message.is_a?(Hash) && message["method"] == "tools/call" && message.key?("id")
|
|
53
|
+
id = message["id"]
|
|
54
|
+
@lock.synchronize do
|
|
55
|
+
@calls[id] = Thread.new do
|
|
56
|
+
reply = respond(message)
|
|
57
|
+
@lock.synchronize { @calls.delete(id) }
|
|
58
|
+
write(reply)
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
elsif message.is_a?(Array)
|
|
62
|
+
replies = message.filter_map { respond(it) }
|
|
63
|
+
write(replies) if replies.any?
|
|
64
|
+
elsif (reply = respond(message))
|
|
65
|
+
write(reply)
|
|
66
|
+
end
|
|
79
67
|
rescue JSON::ParserError
|
|
80
|
-
|
|
68
|
+
write(error_payload(nil, -32700, "Parse error"))
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# Stops the hello and the tool calls still running, and the session's channel.
|
|
72
|
+
def close
|
|
73
|
+
@greeter&.kill
|
|
74
|
+
@greeter = nil
|
|
75
|
+
@lock.synchronize { @calls.values }.each(&:kill)
|
|
76
|
+
session.close
|
|
81
77
|
end
|
|
82
78
|
|
|
83
79
|
private
|
|
@@ -86,83 +82,72 @@ module Tensaku
|
|
|
86
82
|
return error_payload(nil, -32600, "Invalid Request") unless message.is_a?(Hash)
|
|
87
83
|
|
|
88
84
|
id = message["id"]
|
|
89
|
-
|
|
85
|
+
if id.nil? # a notification
|
|
86
|
+
cancel(message.dig("params", "requestId")) if message["method"] == "notifications/cancelled"
|
|
87
|
+
greet if message["method"] == "notifications/initialized"
|
|
88
|
+
return nil
|
|
89
|
+
end
|
|
90
90
|
|
|
91
91
|
result = case message["method"]
|
|
92
|
-
when "initialize" then
|
|
92
|
+
when "initialize" then initialize_result(message["params"].to_h)
|
|
93
93
|
when "ping" then {}
|
|
94
|
-
when "tools/list" then { tools: TOOLS }
|
|
95
|
-
when "tools/call" then
|
|
94
|
+
when "tools/list" then { tools: Session::TOOLS }
|
|
95
|
+
when "tools/call" then session.call(message.dig("params", "name"), message.dig("params", "arguments") || {})
|
|
96
96
|
else return error_payload(id, -32601, "Method not found: #{message["method"]}")
|
|
97
97
|
end
|
|
98
98
|
{ jsonrpc: "2.0", id:, result: }
|
|
99
99
|
end
|
|
100
100
|
|
|
101
|
-
def
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
def initialize_result(requested)
|
|
101
|
+
def initialize_result(params)
|
|
102
|
+
client = params["clientInfo"].to_h
|
|
103
|
+
session.name = (client["title"].presence || client["name"].presence || session.name).to_s.truncate(80)
|
|
104
|
+
# Channels are Claude Code's; other clients get neither the capability nor the hello.
|
|
105
|
+
@claude = [ client["name"], client["title"] ].any? { it.to_s.match?(/claude/i) }
|
|
106
|
+
session.seen!
|
|
107
|
+
requested = params["protocolVersion"]
|
|
108
|
+
capabilities = { tools: { listChanged: false } }
|
|
109
|
+
capabilities[:experimental] = { "claude/channel" => {} } if @claude
|
|
112
110
|
{
|
|
113
111
|
protocolVersion: PROTOCOL_VERSIONS.include?(requested) ? requested : PROTOCOL_VERSIONS.first,
|
|
114
|
-
capabilities
|
|
112
|
+
capabilities:,
|
|
115
113
|
serverInfo: { name: "tensaku", version: Tensaku::VERSION },
|
|
116
|
-
instructions:
|
|
114
|
+
instructions: INSTRUCTIONS + (@claude ? CHANNEL_INSTRUCTIONS : "")
|
|
117
115
|
}
|
|
118
116
|
end
|
|
119
117
|
|
|
120
|
-
def
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
statuses = { "active" => Notes::ACTIVE, "all" => nil }.fetch(status, status)
|
|
125
|
-
checked_at = Time.now.utc.iso8601(6)
|
|
126
|
-
notes = Notes.list(url: arguments["url"].presence, status: statuses)
|
|
127
|
-
tool_result(Notes.to_markdown(notes), notes:, checked_at:)
|
|
128
|
-
when "get_note"
|
|
129
|
-
note = Notes.find(arguments["id"])
|
|
130
|
-
tool_result(Notes.note_markdown(note), note:)
|
|
131
|
-
when "start_note"
|
|
132
|
-
note = Notes.update(arguments["id"], status: "working", agent:)
|
|
133
|
-
tool_result("Started note #{note["id"]}. Resolve it with resolve_note when the change is made.", note:)
|
|
134
|
-
when "resolve_note"
|
|
135
|
-
note = Notes.update(arguments["id"], status: "resolved", message: arguments["reply"], agent:)
|
|
136
|
-
tool_result("Resolved note #{note["id"]}.", note:)
|
|
137
|
-
when "ask_question"
|
|
138
|
-
note = Notes.update(arguments["id"], status: "question", message: arguments["question"], agent:)
|
|
139
|
-
tool_result("Asked on note #{note["id"]}. It shows on the page until the person answers.", note:)
|
|
140
|
-
when "reply_to_note"
|
|
141
|
-
note = Notes.update(arguments["id"], message: arguments["message"], agent:)
|
|
142
|
-
tool_result("Added a message to note #{note["id"]}.", note:)
|
|
143
|
-
when "watch_notes"
|
|
144
|
-
since = arguments["since"].present? ? Time.iso8601(arguments["since"]) : Time.now.utc
|
|
145
|
-
timeout = arguments["timeout_seconds"].to_i.clamp(1, MAX_WATCH)
|
|
146
|
-
timeout = 60 if arguments["timeout_seconds"].nil?
|
|
147
|
-
notes, checked_at = Notes.watch(since:, timeout:)
|
|
148
|
-
text = notes.empty? ? "No new notes in #{timeout}s. Call watch_notes again to keep waiting." : Notes.to_markdown(notes)
|
|
149
|
-
tool_result(text, notes:, checked_at: checked_at.iso8601(6))
|
|
150
|
-
when "current_selection"
|
|
151
|
-
selection = Notes.selection
|
|
152
|
-
tool_result(selection ? JSON.pretty_generate(selection) : "Nothing selected in the Tensaku overlay yet.", selection:)
|
|
153
|
-
else
|
|
154
|
-
tool_result("Unknown tool #{name}", error: true)
|
|
155
|
-
end
|
|
156
|
-
rescue Notes::NotFound, Error, ArgumentError => error
|
|
157
|
-
tool_result(error.message, error: true)
|
|
118
|
+
def greet
|
|
119
|
+
return unless @claude
|
|
120
|
+
|
|
121
|
+
@greeter ||= Thread.new { HELLO_AFTER.each { sleep it; hello } }
|
|
158
122
|
end
|
|
159
123
|
|
|
160
|
-
|
|
161
|
-
|
|
124
|
+
# The first channel message. A session that loaded the channel gets it as a turn and calls
|
|
125
|
+
# channel_ready; any other drops it.
|
|
126
|
+
def hello
|
|
127
|
+
return if session.channel?
|
|
128
|
+
|
|
129
|
+
push("Tensaku is connected as #{session.label}. To have the person's notes pushed into this chat as they save them, call the channel_ready tool with code #{session.channel_code}, then tell the person in one line that their Tensaku notes now arrive here.", kind: "hello")
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def push(content, **meta)
|
|
133
|
+
write({ jsonrpc: "2.0", method: "notifications/claude/channel", params: { content:, meta: meta.transform_values(&:to_s) } })
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
def cancel(id)
|
|
137
|
+
@lock.synchronize { @calls.delete(id) }&.kill
|
|
162
138
|
end
|
|
163
139
|
|
|
164
140
|
def error_payload(id, code, message)
|
|
165
141
|
{ jsonrpc: "2.0", id:, error: { code:, message: } }
|
|
166
142
|
end
|
|
143
|
+
|
|
144
|
+
def write(payload)
|
|
145
|
+
@lock.synchronize do
|
|
146
|
+
@output.write(JSON.generate(payload) + "\n")
|
|
147
|
+
@output.flush
|
|
148
|
+
end
|
|
149
|
+
rescue IOError, Errno::EPIPE
|
|
150
|
+
nil
|
|
151
|
+
end
|
|
167
152
|
end
|
|
168
153
|
end
|
data/lib/tensaku/middleware.rb
CHANGED
|
@@ -85,7 +85,7 @@ module Tensaku
|
|
|
85
85
|
|
|
86
86
|
root = "#{env["SCRIPT_NAME"]}#{Tensaku.config.mount_path}"
|
|
87
87
|
nonce = env[NONCE].presence
|
|
88
|
-
meta = %(<meta name="tensaku" data-tensaku-request="#{ERB::Util.h(env["REQUEST_METHOD"])}" data-tensaku-token="#{Tensaku.token}" data-tensaku-root="#{ERB::Util.h(root)}"
|
|
88
|
+
meta = %(<meta name="tensaku" data-tensaku-request="#{ERB::Util.h(env["REQUEST_METHOD"])}" data-tensaku-token="#{Tensaku.token}" data-tensaku-root="#{ERB::Util.h(root)}">)
|
|
89
89
|
script = %(<script src="#{ERB::Util.h(root)}/tensaku.js?v=#{Endpoints.asset_digest}"#{%( nonce="#{ERB::Util.h(nonce)}") if nonce} data-turbo-eval="false" data-tensaku-ui defer></script>)
|
|
90
90
|
|
|
91
91
|
html = insert_before(html, "</head>", meta) || "#{meta}#{html}"
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
module Tensaku
|
|
2
|
+
module Notes
|
|
3
|
+
# Notes as an agent reads them: the MCP tools' answers, `tensaku notes` and the page's copy button.
|
|
4
|
+
module Markdown
|
|
5
|
+
module_function
|
|
6
|
+
|
|
7
|
+
# app names the app in each heading, for an agent that sees notes from several apps. With
|
|
8
|
+
# latest: true each thread is cut down to what is new (see latest_thread). session, the agent
|
|
9
|
+
# session the list is for, adds whether each note is its own.
|
|
10
|
+
def list(notes, app: nil, latest: false, session: nil)
|
|
11
|
+
notes = Array(notes)
|
|
12
|
+
return "No notes." if notes.empty?
|
|
13
|
+
|
|
14
|
+
base = Project.base_url
|
|
15
|
+
notes.map { note(it, base:, app:, latest:, session:) }.join("\n\n")
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# One line per note, for a chat where the detailed form is too long.
|
|
19
|
+
def short(notes)
|
|
20
|
+
notes = Array(notes)
|
|
21
|
+
return "No notes." if notes.empty?
|
|
22
|
+
|
|
23
|
+
notes.map do |note|
|
|
24
|
+
where = Array(note["targets"]).filter_map { [ it["file"], it["range"]&.split("-")&.first ].compact.join(":").presence }.uniq.first(3)
|
|
25
|
+
"- `#{note["id"]}` (#{note["status"]}) #{note["comment"].squish.truncate(160)}#{" at #{where.map { "`#{it}`" }.join(", ")}" if where.any?}"
|
|
26
|
+
end.join("\n")
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def note(note, base: Project.base_url, app: nil, latest: false, session: nil)
|
|
30
|
+
page = base && note["url"].to_s.start_with?("/") ? "#{base.chomp("/")}#{note["url"]}" : note["url"]
|
|
31
|
+
lines = [ "## Tensaku note #{note["id"]} (#{note["status"]}) on #{page}#{" in #{app}" if app}", "" ]
|
|
32
|
+
if session && ACTIVE.include?(note["status"])
|
|
33
|
+
lines << if note["session"] == session then "*Yours.*"
|
|
34
|
+
elsif note["stopped"] then "*Its session stopped while working on it, so it is nobody's now. Part of the change may already be made: check the file before you redo it. Call start_note to take it.*"
|
|
35
|
+
else "*Nobody's yet: call start_note before you work on it, so no other session takes it.*"
|
|
36
|
+
end
|
|
37
|
+
lines << ""
|
|
38
|
+
end
|
|
39
|
+
lines << note["comment"]
|
|
40
|
+
targets = Array(note["targets"])
|
|
41
|
+
if targets.any?
|
|
42
|
+
lines << ""
|
|
43
|
+
targets.each { lines << "- #{target(it)}" }
|
|
44
|
+
end
|
|
45
|
+
if (rect = note["rect"])
|
|
46
|
+
lines << "" << "Area: #{rect["width"]}x#{rect["height"]} at (#{rect["x"]}, #{rect["y"]}) in a #{note["viewport"] || "unknown"} viewport"
|
|
47
|
+
end
|
|
48
|
+
if (shot = note["screenshot"])
|
|
49
|
+
lines << "" << "Screenshot: #{shot["width"]}x#{shot["height"]} PNG of what the note points at, as the page looked (get_screenshot #{note["id"]}, or `tensaku notes screenshot #{note["id"]}`)"
|
|
50
|
+
end
|
|
51
|
+
thread = Array(note["thread"])
|
|
52
|
+
if thread.any?
|
|
53
|
+
lines << ""
|
|
54
|
+
skipped, thread = latest ? latest_thread(thread) : [ 0, thread ]
|
|
55
|
+
lines << "> *(#{skipped} earlier #{skipped == 1 ? "message" : "messages"}; get_note #{note["id"]} has the whole thread)*" if skipped.positive?
|
|
56
|
+
thread.each { lines << "> **#{it["from"] == "you" ? "You" : (it["agent"] || "Agent")}:** #{it["text"].to_s.gsub("\n", "\n> ")}" }
|
|
57
|
+
end
|
|
58
|
+
lines.join("\n")
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# A long back-and-forth repeated on every watch_notes call costs the agent its context, so a list
|
|
62
|
+
# keeps the agent's latest message and everything after it, and says how many came before.
|
|
63
|
+
def latest_thread(thread)
|
|
64
|
+
last_agent = thread.rindex { it["from"] == "agent" }
|
|
65
|
+
kept = last_agent ? thread[last_agent..] : thread.last(2)
|
|
66
|
+
[ thread.size - kept.size, kept ]
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def target(target)
|
|
70
|
+
location = [ target["file"], target["range"] ].compact.join(":")
|
|
71
|
+
parts = [ target["kind"] ]
|
|
72
|
+
parts << "`#{target["tag"]}`" if target["tag"]
|
|
73
|
+
parts << "`#{target["key"]}` (#{target["locale"]})" if target["key"]
|
|
74
|
+
parts << "at `#{location}`" unless location.empty?
|
|
75
|
+
parts << "\"#{target["text"].to_s.squish.truncate(120)}\"" if target["text"].present?
|
|
76
|
+
parts << "classes `#{Array(target["classes"]).join(" ")}`" if target["classes"].present?
|
|
77
|
+
context = target["context"].to_h.compact_blank
|
|
78
|
+
parts << "(#{context.map { |key, value| "#{key}: #{Array(value).join(" < ")}" }.join(", ")})" if context.any?
|
|
79
|
+
parts.join(" ")
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
end
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
module Tensaku
|
|
2
|
+
module Notes
|
|
3
|
+
# What a note points at, as the overlay sent it, with the file and line filled in from the source:
|
|
4
|
+
# an element (a Herb stamp), a translation key, or a Markdown range.
|
|
5
|
+
module Target
|
|
6
|
+
KINDS = %w[element text translation markdown].freeze
|
|
7
|
+
|
|
8
|
+
module_function
|
|
9
|
+
|
|
10
|
+
# Fills in file positions from what the overlay saw: a Herb stamp, a translation key or a Markdown
|
|
11
|
+
# range. A target whose source can't be read keeps what the page said about it.
|
|
12
|
+
def from(raw)
|
|
13
|
+
raise Error, "A note target must be a JSON object" unless raw.is_a?(Hash)
|
|
14
|
+
|
|
15
|
+
raw = raw.stringify_keys
|
|
16
|
+
kind = KINDS.include?(raw["kind"]) ? raw["kind"] : "element"
|
|
17
|
+
target = { "kind" => kind, "text" => raw["text"]&.to_s&.truncate(500), "tag" => raw["tag"]&.to_s }
|
|
18
|
+
|
|
19
|
+
if raw["stamp"].present?
|
|
20
|
+
target["stamp"] = raw["stamp"].to_s
|
|
21
|
+
path, line, column = Source::Template.parse_stamp(raw["stamp"])
|
|
22
|
+
target["file"] = path
|
|
23
|
+
target["range"] = "#{line}:#{column}"
|
|
24
|
+
begin
|
|
25
|
+
target.merge!(Source::Template.new(path).element_range(line, column).stringify_keys)
|
|
26
|
+
rescue Error
|
|
27
|
+
nil
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
if kind == "translation"
|
|
32
|
+
target["key"] = raw["key"].to_s
|
|
33
|
+
target["locale"] = raw["locale"].to_s
|
|
34
|
+
if (entry = Source::Locale.find(target["locale"], target["key"]))
|
|
35
|
+
target["file"] = entry[:file]
|
|
36
|
+
target["range"] = entry[:line].to_s
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
if kind == "markdown" && raw["md"].present?
|
|
41
|
+
target["md"] = raw["md"].to_s
|
|
42
|
+
target["file"], target["range"] = raw["md"].to_s.split(/:(?=\d+:\d+-)/, 2)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
point = raw["point"]
|
|
46
|
+
target["point"] = point.map { it.to_f.clamp(0.0, 1.0).round(3) } if point.is_a?(Array) && point.size == 2 && point.all?(Numeric)
|
|
47
|
+
target["classes"] = Array(raw["classes"]).map(&:to_s).grep(/\A[^\s]{1,80}\z/).first(12)
|
|
48
|
+
target["context"] = raw["context"].to_h.slice("partials", "controller", "frame").transform_values { Array(it).map(&:to_s).first(10) }.compact_blank
|
|
49
|
+
target.compact_blank
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def rect(raw)
|
|
53
|
+
return nil unless raw.is_a?(Hash)
|
|
54
|
+
|
|
55
|
+
raw.to_h.stringify_keys.slice("x", "y", "width", "height").transform_values { it.to_f.round }
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|