tensaku 0.0.1 → 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 +216 -9
- data/README.md +40 -166
- data/app/assets/tensaku.js +352 -65
- data/exe/tensaku +5 -0
- data/lib/generators/tensaku/install_generator.rb +112 -51
- 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 +128 -37
- data/lib/tensaku/file_write.rb +30 -0
- data/lib/tensaku/guard.rb +73 -17
- data/lib/tensaku/i18n.rb +19 -1
- data/lib/tensaku/mcp.rb +114 -96
- data/lib/tensaku/middleware.rb +48 -8
- data/lib/tensaku/notes/markdown.rb +83 -0
- data/lib/tensaku/notes/target.rb +59 -0
- data/lib/tensaku/notes.rb +257 -127
- 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/html_text.rb +9 -3
- data/lib/tensaku/source/locale.rb +25 -13
- data/lib/tensaku/source/markdown.rb +36 -8
- data/lib/tensaku/source/template.rb +26 -4
- data/lib/tensaku/store.rb +196 -0
- data/lib/tensaku/version.rb +1 -1
- data/lib/tensaku.rb +75 -16
- data/skills/tensaku/SKILL.md +58 -16
- metadata +52 -13
data/lib/tensaku/railtie.rb
CHANGED
|
@@ -6,14 +6,29 @@ module Tensaku
|
|
|
6
6
|
require "reactionview"
|
|
7
7
|
require "herb/engine/visitors/source_attribution_visitor"
|
|
8
8
|
|
|
9
|
+
# Stamps without Herb's recommended `action_view_helpers`, which drops the attributes of
|
|
10
|
+
# `tag.div(**attrs)` in Herb 0.11.2. Without it, helpers render as they do in production and
|
|
11
|
+
# their output has no stamp of its own. An app can still set the option in
|
|
12
|
+
# config/initializers/reactionview.rb to get those stamps.
|
|
13
|
+
class SourceStamps < Herb::Engine::SourceAttributionVisitor
|
|
14
|
+
def recommended_parser_options = super.except(:action_view_helpers)
|
|
15
|
+
end
|
|
16
|
+
|
|
9
17
|
# Before the app's initializers, so config/initializers/reactionview.rb can still adjust things.
|
|
10
18
|
initializer "tensaku.reactionview", before: :load_config_initializers do
|
|
11
19
|
ReActionView.configure do |config|
|
|
12
20
|
config.intercept_erb = true
|
|
13
|
-
|
|
21
|
+
# Herb's dev tools aren't needed here, and their script warns when Herb's dev server isn't running.
|
|
22
|
+
config.debug_mode = false
|
|
23
|
+
config.engine.visitors.use(SourceStamps.new)
|
|
14
24
|
end
|
|
15
25
|
end
|
|
16
26
|
|
|
27
|
+
# The code this server runs, to tell the page when the files changed under it (Build.stale?).
|
|
28
|
+
initializer "tensaku.build" do
|
|
29
|
+
Tensaku::Build.started
|
|
30
|
+
end
|
|
31
|
+
|
|
17
32
|
initializer "tensaku.middleware" do |app|
|
|
18
33
|
app.middleware.insert_before 0, Tensaku::Middleware
|
|
19
34
|
end
|
data/lib/tensaku/repo.rb
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
module Tensaku
|
|
2
|
+
# What a note records about the code it was written against: the commit checked out and the origin
|
|
3
|
+
# remote. Read from the files in .git, without running git, and nil when there is no repository.
|
|
4
|
+
module Repo
|
|
5
|
+
module_function
|
|
6
|
+
|
|
7
|
+
def head(root)
|
|
8
|
+
git = git_dir(root) or return nil
|
|
9
|
+
ref = git.join("HEAD").read.strip
|
|
10
|
+
return ref if ref.match?(/\A\h{40}\z/)
|
|
11
|
+
|
|
12
|
+
name = ref.delete_prefix("ref: ")
|
|
13
|
+
common = common_dir(git)
|
|
14
|
+
[ git, common ].uniq.each do |dir|
|
|
15
|
+
file = dir.join(name)
|
|
16
|
+
return file.read.strip if file.file?
|
|
17
|
+
end
|
|
18
|
+
packed = common.join("packed-refs")
|
|
19
|
+
packed.file? ? packed.each_line.find { it.strip.end_with?(" #{name}") }&.split&.first : nil
|
|
20
|
+
rescue SystemCallError
|
|
21
|
+
nil
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def remote(root)
|
|
25
|
+
git = git_dir(root) or return nil
|
|
26
|
+
config = common_dir(git).join("config")
|
|
27
|
+
return nil unless config.file?
|
|
28
|
+
|
|
29
|
+
section = nil
|
|
30
|
+
config.each_line do |line|
|
|
31
|
+
section = line.strip if line.strip.start_with?("[")
|
|
32
|
+
return line.split("=", 2).last.strip if section == '[remote "origin"]' && line.strip.start_with?("url")
|
|
33
|
+
end
|
|
34
|
+
nil
|
|
35
|
+
rescue SystemCallError
|
|
36
|
+
nil
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# The .git directory of root or the nearest folder above it. In a worktree .git is a file that
|
|
40
|
+
# points at it.
|
|
41
|
+
def git_dir(root)
|
|
42
|
+
Pathname(root).expand_path.ascend do |dir|
|
|
43
|
+
dot = dir.join(".git")
|
|
44
|
+
return dot if dot.directory?
|
|
45
|
+
return Pathname(dot.read[/\Agitdir: (.+)$/, 1].to_s.strip).expand_path(dir) if dot.file?
|
|
46
|
+
end
|
|
47
|
+
nil
|
|
48
|
+
rescue SystemCallError
|
|
49
|
+
nil
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def common_dir(git)
|
|
53
|
+
file = git.join("commondir")
|
|
54
|
+
file.file? ? Pathname(file.read.strip).expand_path(git) : git
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
require "json"
|
|
2
|
+
|
|
3
|
+
module Tensaku
|
|
4
|
+
class Session
|
|
5
|
+
# The tools an agent calls, each described for MCP's tools/list (TOOLS) and answered by the method of
|
|
6
|
+
# the same name. Mcp lists them; `tensaku notes` maps its commands onto them (CLI::NOTE_COMMANDS).
|
|
7
|
+
#
|
|
8
|
+
# Replies are text only. A reply that repeated itself as structured data would cost an agent the
|
|
9
|
+
# tokens twice, and a state change only needs an acknowledgement.
|
|
10
|
+
module Tools
|
|
11
|
+
BY_ID = { type: "object", properties: { id: { type: "string" } }, required: %w[id] }.freeze
|
|
12
|
+
|
|
13
|
+
TOOLS = [
|
|
14
|
+
{
|
|
15
|
+
name: "list_notes",
|
|
16
|
+
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), sent or not.",
|
|
17
|
+
inputSchema: {
|
|
18
|
+
type: "object",
|
|
19
|
+
properties: {
|
|
20
|
+
status: { type: "string", enum: %w[open working question resolved declined active archived all], description: "active (default) means open, working or question. archived lists the archive; all is every note outside it." },
|
|
21
|
+
url: { type: "string", description: "Only notes left on this path, for example /about." }
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
name: "get_note",
|
|
27
|
+
description: "Get one Tensaku note by id.",
|
|
28
|
+
inputSchema: BY_ID
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
name: "get_screenshot",
|
|
32
|
+
description: "Get the screenshot the page took of what a note points at, as a PNG, when the note says it has one. It shows the page as the person saw it when writing the note.",
|
|
33
|
+
inputSchema: BY_ID
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
name: "start_note",
|
|
37
|
+
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, and the note becomes this session's. Fails when the note belongs to another running agent session: then leave it. Call resolve_note as soon as the change is made.",
|
|
38
|
+
inputSchema: BY_ID
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
name: "resolve_note",
|
|
42
|
+
description: "Mark a note resolved as soon as its change is made, before starting the next note. Only a note you started with start_note can be resolved. The person is watching the page, so don't save these up for the end. The reply is shown next to a green pin: say in one line what changed and where (for example: changed the heading in app/views/pages/_hero.html.erb:4).",
|
|
43
|
+
inputSchema: { type: "object", properties: { id: { type: "string" }, reply: { type: "string" } }, required: %w[id reply] }
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
name: "decline_note",
|
|
47
|
+
description: "Close a note without changing anything, when the change shouldn't be made or can't be made here. The reason is shown on the page next to the note.",
|
|
48
|
+
inputSchema: { type: "object", properties: { id: { type: "string" }, reason: { type: "string" } }, required: %w[id reason] }
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
name: "ask_question",
|
|
52
|
+
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 on the note.",
|
|
53
|
+
inputSchema: { type: "object", properties: { id: { type: "string" }, question: { type: "string" } }, required: %w[id question] }
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: "reply_to_note",
|
|
57
|
+
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.",
|
|
58
|
+
inputSchema: { type: "object", properties: { id: { type: "string" }, message: { type: "string" } }, required: %w[id message] }
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
name: "watch_notes",
|
|
62
|
+
description: "Wait for notes the person saves on the page, so you can work through them as they arrive. Returns as soon as there are any, or empty after the timeout. While you wait, the page shows you as listening. Pass the checked_at value of the previous call as since so nothing is missed, and call it again after working through the notes to keep listening.",
|
|
63
|
+
inputSchema: {
|
|
64
|
+
type: "object",
|
|
65
|
+
properties: {
|
|
66
|
+
since: { type: "string", description: "ISO 8601 time. Defaults to now." },
|
|
67
|
+
timeout_seconds: { type: "integer", minimum: 1, maximum: MAX_WATCH, description: "Defaults to 60." }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
name: "channel_ready",
|
|
73
|
+
description: "Only when a Tensaku channel event asks for it: confirms that Tensaku's channel messages reach this session, so the person's notes are pushed here as they save them.",
|
|
74
|
+
inputSchema: { type: "object", properties: { code: { type: "string", description: "The code from the channel event" } }, required: %w[code] }
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
name: "current_selection",
|
|
78
|
+
description: "What the person last selected in the Tensaku overlay (elements with file and line), for questions like 'what is this?'.",
|
|
79
|
+
inputSchema: { type: "object", properties: {} }
|
|
80
|
+
}
|
|
81
|
+
].freeze
|
|
82
|
+
|
|
83
|
+
NAMES = TOOLS.map { it[:name] }.freeze
|
|
84
|
+
|
|
85
|
+
private
|
|
86
|
+
|
|
87
|
+
# Lists this session's notes. Notes another running session owns are left out and counted.
|
|
88
|
+
def list_notes(arguments)
|
|
89
|
+
status = arguments["status"].presence || "active"
|
|
90
|
+
status = { "active" => Notes::ACTIVE, "all" => nil }.fetch(status, status)
|
|
91
|
+
url = arguments["url"].presence
|
|
92
|
+
@checked_at = Time.now.utc
|
|
93
|
+
listed = per_app { Notes.list(url:, status:).partition { Notes.available_to?(it, id) } }
|
|
94
|
+
mine = listed.map { |app, (notes, _)| [ app, notes ] }
|
|
95
|
+
taken = listed.sum { |_, (_, others)| others.size }
|
|
96
|
+
text = notes_markdown(mine).presence || "No notes."
|
|
97
|
+
text += "\n\n#{taken} more #{taken == 1 ? "note belongs" : "notes belong"} to other running agent sessions and #{taken == 1 ? "isn't" : "aren't"} listed. Leave #{taken == 1 ? "it" : "them"} to those sessions." if taken.positive?
|
|
98
|
+
result(text)
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def get_note(arguments)
|
|
102
|
+
app, note = Notes.locate(apps, arguments["id"])
|
|
103
|
+
result(Tensaku.with_root(app) { Notes::Markdown.note(note, app: app_label(app)) })
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
def get_screenshot(arguments)
|
|
107
|
+
shot = in_app_of(arguments["id"]) { Notes.screenshot(arguments["id"]) }
|
|
108
|
+
return result("Note #{arguments["id"]} has no screenshot.", error: true) unless shot
|
|
109
|
+
|
|
110
|
+
{ content: [ { type: "image", data: [ shot["png"] ].pack("m0"), mimeType: "image/png" } ], isError: false }
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def start_note(arguments)
|
|
114
|
+
note = in_app_of(arguments["id"]) { Notes.start(arguments["id"], agent: label, session: id) }
|
|
115
|
+
result("Started note #{note["id"]}. The page shows you as #{label}.")
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def resolve_note(arguments)
|
|
119
|
+
note = change(arguments["id"], status: "resolved", message: arguments["reply"], started: true)
|
|
120
|
+
result("Resolved note #{note["id"]}.#{" Call watch_notes to keep listening." if @watched && !@channel}")
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def decline_note(arguments)
|
|
124
|
+
note = change(arguments["id"], status: "declined", message: arguments["reason"])
|
|
125
|
+
result("Declined note #{note["id"]}.")
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def ask_question(arguments)
|
|
129
|
+
note = change(arguments["id"], status: "question", message: arguments["question"])
|
|
130
|
+
result("Asked on note #{note["id"]}.")
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def reply_to_note(arguments)
|
|
134
|
+
note = change(arguments["id"], message: arguments["message"])
|
|
135
|
+
result("Added a message to note #{note["id"]}.")
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
def watch_notes(arguments)
|
|
139
|
+
since = arguments["since"].present? ? Time.iso8601(arguments["since"]) : Time.now.utc
|
|
140
|
+
timeout = arguments["timeout_seconds"].nil? ? 60 : arguments["timeout_seconds"].to_i.clamp(1, MAX_WATCH)
|
|
141
|
+
first = !@watched
|
|
142
|
+
@watched = true
|
|
143
|
+
found, checked_at = watch(since, timeout)
|
|
144
|
+
@checked_at = [ @checked_at, checked_at ].max
|
|
145
|
+
text = found.empty? ? "No new notes in #{timeout}s." : notes_markdown(found)
|
|
146
|
+
intro = "You are listening as #{label}. Tell the person this name: the page shows it, and the notes handed to you are yours.\n\n" if first
|
|
147
|
+
result("#{intro}#{text}\n\nchecked_at: #{checked_at.iso8601(6)}").merge(handed: ids(found))
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
def channel_ready(arguments)
|
|
151
|
+
return result("That isn't the code from Tensaku's channel event.", error: true) unless @push && arguments["code"].to_s == channel_code
|
|
152
|
+
|
|
153
|
+
start_channel
|
|
154
|
+
waiting = per_app { Notes.list(status: Notes::ACTIVE, session: id).size }.sum(&:last)
|
|
155
|
+
result("Tensaku's channel works. Notes the person saves on the page arrive in this chat as #{label}, already yours. Tell the person in one line#{", and that #{waiting} earlier #{waiting == 1 ? "note is" : "notes are"} open (list_notes has them), without starting on them unless they ask" if waiting.positive?}.")
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def current_selection(_arguments)
|
|
159
|
+
selection = per_app { Project.selection }.filter_map(&:last).max_by { it["at"].to_s }
|
|
160
|
+
result(selection ? JSON.pretty_generate(selection) : "Nothing selected in the Tensaku overlay yet.")
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
end
|
|
164
|
+
end
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
require "json"
|
|
2
|
+
require "securerandom"
|
|
3
|
+
|
|
4
|
+
module Tensaku
|
|
5
|
+
# One agent session over one or more apps, behind `tensaku mcp` (Mcp) and `tensaku notes` (CLI). It
|
|
6
|
+
# answers the tools in Session::Tools, and runs without Rails on Tensaku's database for each app.
|
|
7
|
+
#
|
|
8
|
+
# While it runs it checks in to each app's agents table (Agents.seen!), so the page shows the agent as
|
|
9
|
+
# connected, and as listening while a watch_notes call waits.
|
|
10
|
+
#
|
|
11
|
+
# Claude Code channels: given a push (Mcp passes one that writes a channel notification), the session
|
|
12
|
+
# sends Mcp's hello with channel_code and treats the channel as working once the agent calls
|
|
13
|
+
# channel_ready with that code. From then on it claims each note saved on the page, as watch_notes
|
|
14
|
+
# would, and pushes it into the session.
|
|
15
|
+
class Session
|
|
16
|
+
autoload :Tools, "tensaku/session/tools"
|
|
17
|
+
|
|
18
|
+
MAX_WATCH = 300
|
|
19
|
+
HEARTBEAT = 5
|
|
20
|
+
# A watch sleeps on the doorbell, and looks anyway this often, for a note whose owner went away.
|
|
21
|
+
RECHECK = 10
|
|
22
|
+
LOG = "tmp/tensaku/mcp.log"
|
|
23
|
+
LOG_LIMIT = 1_000_000
|
|
24
|
+
|
|
25
|
+
include Tools
|
|
26
|
+
|
|
27
|
+
attr_reader :apps, :id, :channel_code
|
|
28
|
+
attr_accessor :name
|
|
29
|
+
|
|
30
|
+
# apps are the root directories of the Rails apps to serve. push(content, **meta) sends a message
|
|
31
|
+
# into the agent's chat, when the client supports one.
|
|
32
|
+
def initialize(apps, name: "MCP agent", push: nil)
|
|
33
|
+
@apps = apps.map { Pathname(it).expand_path }
|
|
34
|
+
@id = SecureRandom.hex(16)
|
|
35
|
+
@name = name
|
|
36
|
+
@push = push
|
|
37
|
+
@listening = 0
|
|
38
|
+
@started_at = Time.now.utc.iso8601
|
|
39
|
+
# When this agent last saw the sent notes (list_notes or watch_notes), for the line that tells a
|
|
40
|
+
# busy agent about notes sent since.
|
|
41
|
+
@checked_at = Time.now.utc
|
|
42
|
+
@watched = false
|
|
43
|
+
@last = nil
|
|
44
|
+
@lock = Mutex.new
|
|
45
|
+
@seen_lock = Mutex.new
|
|
46
|
+
@claim_lock = Mutex.new
|
|
47
|
+
@channel_code = SecureRandom.alphanumeric(8)
|
|
48
|
+
@channel = false
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def channel? = @channel
|
|
52
|
+
|
|
53
|
+
# A thread that checks in every HEARTBEAT seconds, for a long-running session. Kill it before close.
|
|
54
|
+
def heartbeat
|
|
55
|
+
Thread.new { loop { seen!; sleep HEARTBEAT } }
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# Takes this session off the page and stops pushing notes.
|
|
59
|
+
def close
|
|
60
|
+
@pusher&.kill
|
|
61
|
+
@pusher = nil
|
|
62
|
+
each_app { Agents.gone!(id) }
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# One writer at a time, so the heartbeat can't write an old name or state over a newer one.
|
|
66
|
+
def seen!
|
|
67
|
+
@seen_lock.synchronize do
|
|
68
|
+
each_app do
|
|
69
|
+
Agents.seen!(id, name: @name, handle:, listening: @listening.positive?, channel: @channel, cwd: Dir.pwd, started_at: @started_at, last: @last)
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
rescue SystemCallError, SQLite3::BusyException
|
|
73
|
+
nil # a database busy for longer than its timeout is tried again at the next heartbeat
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# Two words for this session, such as amber-fox, that no other connected session of its first app
|
|
77
|
+
# has. Chosen once.
|
|
78
|
+
def handle
|
|
79
|
+
@handle ||= Tensaku.with_root(apps.first) { Agents.free_handle(id) }
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# The client's name and this session's handle, as notes and the page show it: "Claude Code · amber-fox".
|
|
83
|
+
def label
|
|
84
|
+
"#{@name} · #{handle}"
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Records the call for the page, runs it, and tells the agent about notes sent since it last
|
|
88
|
+
# looked: a session that has listened gets them in the answer, claimed like watch_notes would, so
|
|
89
|
+
# it doesn't have to wait in watch_notes while it works. Any other session gets their ids.
|
|
90
|
+
# Returns an MCP tool result: { content: [...], isError: }.
|
|
91
|
+
def call(name, arguments = {})
|
|
92
|
+
arguments = arguments.transform_keys(&:to_s)
|
|
93
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
94
|
+
@last = { "tool" => name.to_s, "note" => arguments["id"].presence, "at" => Time.now.utc.iso8601 }.compact
|
|
95
|
+
seen!
|
|
96
|
+
result = run(name, arguments)
|
|
97
|
+
handed = result.delete(:handed) || (news(result) unless result[:isError] || %w[list_notes watch_notes].include?(name))
|
|
98
|
+
log(name, started, result, handed)
|
|
99
|
+
result
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
private
|
|
103
|
+
|
|
104
|
+
def run(name, arguments)
|
|
105
|
+
return result("Unknown tool #{name}", error: true) unless Tools::NAMES.include?(name.to_s)
|
|
106
|
+
|
|
107
|
+
send(name.to_s, arguments)
|
|
108
|
+
rescue Error, ArgumentError => error
|
|
109
|
+
result(error.message, error: true)
|
|
110
|
+
rescue StandardError => error
|
|
111
|
+
warn "[Tensaku] #{error.class}: #{error.message}\n#{Array(error.backtrace).first(10).join("\n")}"
|
|
112
|
+
result("Tensaku hit an error: #{error.class}: #{error.message}", error: true)
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
def news(result)
|
|
116
|
+
if @watched
|
|
117
|
+
found = claim_since(@checked_at)
|
|
118
|
+
return [] if found.empty?
|
|
119
|
+
|
|
120
|
+
result[:content] << { type: "text", text: "Notes the person saved while you worked. They are yours now; work through them next:\n\n#{notes_markdown(found)}" }
|
|
121
|
+
ids(found)
|
|
122
|
+
else
|
|
123
|
+
now = Time.now.utc
|
|
124
|
+
sent = per_app { Notes.sent_between(@checked_at, now, session: id) }.flat_map(&:last).map { it["id"] }
|
|
125
|
+
result[:content] << { type: "text", text: "#{sent.size == 1 ? "1 note was" : "#{sent.size} notes were"} saved on the page since you last looked (#{sent.join(", ")}). Call watch_notes or list_notes next." } if sent.any?
|
|
126
|
+
[]
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# Waits until a note is sent in any app, or the timeout passes, and claims what it finds for this
|
|
131
|
+
# session. Returns [[app, notes], ...] and the time to pass as the next since. The time is taken
|
|
132
|
+
# before the scan; see Notes.sent_between.
|
|
133
|
+
#
|
|
134
|
+
# It waits on the doorbell and only scans an app whose notes changed since the last scan. The
|
|
135
|
+
# version is read in a write transaction, after checked_at: a note sent before checked_at was
|
|
136
|
+
# committed before the transaction could start, so it shows in the version.
|
|
137
|
+
def watch(since, timeout)
|
|
138
|
+
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
|
|
139
|
+
versions = {}
|
|
140
|
+
listening(+1)
|
|
141
|
+
Doorbell.listen(apps) do |doorbell|
|
|
142
|
+
loop do
|
|
143
|
+
checked_at = Time.now.utc
|
|
144
|
+
found = apps.filter_map do |app|
|
|
145
|
+
Tensaku.with_root(app) do
|
|
146
|
+
version = Project.write { Project.version }
|
|
147
|
+
next if versions[app] == version
|
|
148
|
+
|
|
149
|
+
versions[app] = version
|
|
150
|
+
notes = Notes.claim_sent(since, checked_at, session: id, agent: label)
|
|
151
|
+
[ app, notes ] if notes.any?
|
|
152
|
+
end
|
|
153
|
+
end
|
|
154
|
+
left = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
155
|
+
return [ found, checked_at ] if found.any? || left <= 0
|
|
156
|
+
|
|
157
|
+
doorbell.wait([ left, RECHECK ].min)
|
|
158
|
+
end
|
|
159
|
+
end
|
|
160
|
+
ensure
|
|
161
|
+
listening(-1)
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# Claims the notes sent since time in every app, for an answer that isn't watch_notes.
|
|
165
|
+
def claim_since(time)
|
|
166
|
+
@claim_lock.synchronize do
|
|
167
|
+
now = Time.now.utc
|
|
168
|
+
found = apps.filter_map do |app|
|
|
169
|
+
notes = Tensaku.with_root(app) { Notes.claim_sent(time, now, session: id, agent: label) }
|
|
170
|
+
[ app, notes ] if notes.any?
|
|
171
|
+
end
|
|
172
|
+
@checked_at = [ @checked_at, now ].max
|
|
173
|
+
found
|
|
174
|
+
end
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
def start_channel
|
|
178
|
+
return if @channel
|
|
179
|
+
|
|
180
|
+
@channel = true
|
|
181
|
+
@watched = true
|
|
182
|
+
@checked_at = Time.now.utc
|
|
183
|
+
listening(+1)
|
|
184
|
+
@pusher = Thread.new { push_notes }
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
# Claims the notes saved on the page as they come and pushes them into the session, for as long as
|
|
188
|
+
# the process runs. The doorbell wakes it at once; it also looks every RECHECK seconds, for a note
|
|
189
|
+
# whose owner went away.
|
|
190
|
+
def push_notes
|
|
191
|
+
Doorbell.listen(apps) do |doorbell|
|
|
192
|
+
loop do
|
|
193
|
+
found = claim_since(@checked_at)
|
|
194
|
+
if found.any?
|
|
195
|
+
@push.call("Notes the person saved on the page. They are yours: work through them one at a time with start_note and resolve_note.\n\n#{notes_markdown(found)}", kind: "notes", notes: ids(found).join(" "))
|
|
196
|
+
log("channel", Process.clock_gettime(Process::CLOCK_MONOTONIC), { content: [] }, ids(found))
|
|
197
|
+
end
|
|
198
|
+
doorbell.wait(RECHECK)
|
|
199
|
+
end
|
|
200
|
+
end
|
|
201
|
+
rescue StandardError => error
|
|
202
|
+
warn "[Tensaku] channel: #{error.class}: #{error.message}"
|
|
203
|
+
@pusher = nil
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
# One JSON line per tool call in each app's tmp/tensaku/mcp.log: which session, the tool, how long
|
|
207
|
+
# it took, how big the answer was and the notes it handed over, to see what Tensaku costs an agent.
|
|
208
|
+
def log(tool, started, result, handed)
|
|
209
|
+
line = JSON.generate({
|
|
210
|
+
at: Time.now.utc.iso8601(3), session: handle, agent: @name, tool:,
|
|
211
|
+
ms: ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round,
|
|
212
|
+
bytes: result[:content].sum { it[:text].to_s.bytesize }, notes: Array(handed).presence, error: result[:isError] || nil
|
|
213
|
+
}.compact) + "\n"
|
|
214
|
+
each_app do
|
|
215
|
+
path = Tensaku.root.join(LOG)
|
|
216
|
+
path.dirname.mkpath
|
|
217
|
+
File.rename(path, "#{path}.1") if path.file? && path.size > LOG_LIMIT
|
|
218
|
+
File.write(path, line, mode: "a")
|
|
219
|
+
end
|
|
220
|
+
rescue SystemCallError
|
|
221
|
+
nil
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
def listening(change)
|
|
225
|
+
@lock.synchronize { @listening += change }
|
|
226
|
+
seen!
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
def each_app(&block)
|
|
230
|
+
apps.each { |app| Tensaku.with_root(app, &block) }
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
# Runs the block in each app: [[app, value], ...].
|
|
234
|
+
def per_app(&block)
|
|
235
|
+
apps.map { |app| [ app, Tensaku.with_root(app, &block) ] }
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
def change(note_id, **changes)
|
|
239
|
+
in_app_of(note_id) { Notes.update(note_id, agent: label, session: id, **changes) }
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
def in_app_of(note_id, &block)
|
|
243
|
+
app, = Notes.locate(apps, note_id)
|
|
244
|
+
Tensaku.with_root(app, &block)
|
|
245
|
+
end
|
|
246
|
+
|
|
247
|
+
# Notes from several apps ([[app, notes], ...]) as one Markdown text, or "" when there are none.
|
|
248
|
+
def notes_markdown(found)
|
|
249
|
+
found.filter_map do |app, notes|
|
|
250
|
+
Tensaku.with_root(app) { Notes::Markdown.list(notes, app: app_label(app), latest: true, session: id) } if notes.any?
|
|
251
|
+
end.join("\n\n")
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
def ids(found)
|
|
255
|
+
found.flat_map { |_, notes| notes.map { it["id"] } }
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
# The app's name in headings, when there is more than one app.
|
|
259
|
+
def app_label(app)
|
|
260
|
+
app.basename.to_s if apps.size > 1
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
def result(text, error: false)
|
|
264
|
+
{ content: [ { type: "text", text: } ], isError: error }
|
|
265
|
+
end
|
|
266
|
+
end
|
|
267
|
+
end
|
|
@@ -19,6 +19,7 @@ module Tensaku
|
|
|
19
19
|
"iexcl" => "\u00A1", "iquest" => "\u00BF", "larr" => "\u2190", "rarr" => "\u2192"
|
|
20
20
|
}.freeze
|
|
21
21
|
|
|
22
|
+
NBSP = "\u00A0"
|
|
22
23
|
WHITESPACE = /\A[ \t\r\n\f]+\z/
|
|
23
24
|
TOKEN = /&(?:#[xX]\h+|#\d+|[a-zA-Z][a-zA-Z0-9]*);|[ \t\r\n\f]+|./m
|
|
24
25
|
|
|
@@ -41,8 +42,13 @@ module Tensaku
|
|
|
41
42
|
end
|
|
42
43
|
|
|
43
44
|
# The new source for this text after an edit, changing only the segments the edit touched.
|
|
45
|
+
#
|
|
46
|
+
# Browsers hand back a non-breaking space for ` ` and for runs of typed spaces, so the two
|
|
47
|
+
# compare as equal: an untouched ` ` keeps its source, and a non-breaking space in the
|
|
48
|
+
# changed part is written as a plain space.
|
|
44
49
|
def rewrite(new_text, escape:)
|
|
45
|
-
old_text = text
|
|
50
|
+
old_text = text.tr(NBSP, " ")
|
|
51
|
+
new_text = new_text.tr(NBSP, " ")
|
|
46
52
|
return @raw if new_text == old_text
|
|
47
53
|
|
|
48
54
|
prefix = common_prefix(old_text, new_text)
|
|
@@ -58,12 +64,12 @@ module Tensaku
|
|
|
58
64
|
end
|
|
59
65
|
|
|
60
66
|
def self.escape_text(text)
|
|
61
|
-
text.gsub("&", "&").gsub("<", "<").gsub(">", ">")
|
|
67
|
+
text.gsub("&", "&").gsub("<", "<").gsub(">", ">")
|
|
62
68
|
end
|
|
63
69
|
|
|
64
70
|
def self.attribute_escaper(quote)
|
|
65
71
|
lambda do |text|
|
|
66
|
-
escaped = text
|
|
72
|
+
escaped = escape_text(text)
|
|
67
73
|
quote == "'" ? escaped.gsub("'", "'") : escaped.gsub('"', """)
|
|
68
74
|
end
|
|
69
75
|
end
|
|
@@ -9,7 +9,7 @@ module Tensaku
|
|
|
9
9
|
EXTENSIONS = %w[.yml .yaml].freeze
|
|
10
10
|
INTERPOLATION = /%\{[^}]+\}/
|
|
11
11
|
|
|
12
|
-
Entry = Data.define(:file, :path, :source, :node, :value) do
|
|
12
|
+
Entry = Data.define(:file, :path, :source, :node, :value, :flow) do
|
|
13
13
|
def line = node.start_line + 1
|
|
14
14
|
|
|
15
15
|
def to_h
|
|
@@ -24,8 +24,8 @@ module Tensaku
|
|
|
24
24
|
def find(locale, key)
|
|
25
25
|
candidates(locale).reverse_each do |relative, path|
|
|
26
26
|
source = File.read(path, mode: "rb").force_encoding(Encoding::UTF_8)
|
|
27
|
-
node = scalar_at(Psych.parse(source), [ locale.to_s, *key.to_s.split(".") ])
|
|
28
|
-
return Entry.new(relative, path, source, node, node.value) if node
|
|
27
|
+
node, flow = scalar_at(Psych.parse(source), [ locale.to_s, *key.to_s.split(".") ])
|
|
28
|
+
return Entry.new(relative, path, source, node, node.value, flow) if node
|
|
29
29
|
rescue Psych::SyntaxError
|
|
30
30
|
next
|
|
31
31
|
end
|
|
@@ -57,7 +57,7 @@ module Tensaku
|
|
|
57
57
|
|
|
58
58
|
check!(updated, locale, key, text, entry.file)
|
|
59
59
|
FileWrite.atomic(entry.path, updated)
|
|
60
|
-
{ changed: true, file: entry.file, line: entry.line }
|
|
60
|
+
{ changed: true, file: entry.file, line: entry.line, diff: FileWrite.diff(entry.source, updated) }
|
|
61
61
|
end
|
|
62
62
|
|
|
63
63
|
def style_name(style)
|
|
@@ -67,37 +67,47 @@ module Tensaku
|
|
|
67
67
|
end
|
|
68
68
|
|
|
69
69
|
def candidates(locale)
|
|
70
|
-
allowed = Guard.writable_dirs.map(&:to_s)
|
|
71
70
|
root = Tensaku.root.realpath
|
|
72
71
|
I18n.load_path.flatten.filter_map do |entry|
|
|
73
72
|
path = Pathname(entry.to_s).expand_path
|
|
74
73
|
next unless EXTENSIONS.include?(path.extname) && path.file?
|
|
75
74
|
|
|
76
75
|
path = path.realpath
|
|
77
|
-
next unless
|
|
76
|
+
next unless Guard.writable?(path)
|
|
78
77
|
|
|
79
78
|
[ path.relative_path_from(root).to_s, path ]
|
|
80
79
|
end.uniq.select { |_, path| File.read(path).include?(locale.to_s) }
|
|
81
80
|
end
|
|
82
81
|
|
|
82
|
+
# The scalar at the key path, and whether it sits inside a flow collection (`{a: Hi}`), where a
|
|
83
|
+
# plain value can't contain `,` or brackets.
|
|
83
84
|
def scalar_at(document, keys)
|
|
84
85
|
node = document&.root
|
|
86
|
+
flow = false
|
|
85
87
|
keys.each do |key|
|
|
86
88
|
return nil unless node.is_a?(Psych::Nodes::Mapping)
|
|
87
89
|
|
|
90
|
+
flow ||= node.style == Psych::Nodes::Mapping::FLOW
|
|
88
91
|
pair = node.children.each_slice(2).to_a.reverse.find { |name, _| name.is_a?(Psych::Nodes::Scalar) && name.value == key }
|
|
89
92
|
return nil unless pair
|
|
90
93
|
|
|
91
94
|
node = pair.last
|
|
92
95
|
end
|
|
93
|
-
node if node.is_a?(Psych::Nodes::Scalar)
|
|
96
|
+
[ node, flow ] if node.is_a?(Psych::Nodes::Scalar)
|
|
94
97
|
end
|
|
95
98
|
|
|
96
|
-
# Psych positions are 0-based lines and character columns.
|
|
99
|
+
# Psych positions are 0-based lines and character columns. A scalar's start includes its anchor
|
|
100
|
+
# (`&name`) and tag (`!!str`); the range starts after them, so they stay as written.
|
|
97
101
|
def byte_range(source, node)
|
|
98
102
|
lines = source.lines
|
|
99
103
|
offset = ->(line, column) { lines.first(line).sum(&:bytesize) + lines.fetch(line, "")[0, column].to_s.bytesize }
|
|
100
|
-
|
|
104
|
+
start = offset.call(node.start_line, node.start_column)
|
|
105
|
+
finish = offset.call(node.end_line, node.end_column)
|
|
106
|
+
if node.anchor || node.tag
|
|
107
|
+
properties = source.byteslice(start...finish).b[/\A(?:(?:&\S+|!\S*)[ \t]+)+/n]
|
|
108
|
+
start += properties.bytesize if properties
|
|
109
|
+
end
|
|
110
|
+
[ start, finish ]
|
|
101
111
|
end
|
|
102
112
|
|
|
103
113
|
# The new scalar in the style the old one had. A plain scalar that would read differently as
|
|
@@ -111,7 +121,7 @@ module Tensaku
|
|
|
111
121
|
when Psych::Nodes::Scalar::LITERAL, Psych::Nodes::Scalar::FOLDED
|
|
112
122
|
block(entry, text, old)
|
|
113
123
|
else
|
|
114
|
-
plain_safe?(text) ? text : double_quoted(text)
|
|
124
|
+
plain_safe?(text) && !(entry.flow && text.match?(/[,\[\]{}]/)) ? text : double_quoted(text)
|
|
115
125
|
end
|
|
116
126
|
end
|
|
117
127
|
|
|
@@ -131,16 +141,18 @@ module Tensaku
|
|
|
131
141
|
|
|
132
142
|
# Keeps the header (`>-`, `|+`), the indentation and any trailing blank lines of a block scalar.
|
|
133
143
|
def block(entry, text, old)
|
|
144
|
+
eol = entry.source.include?("\r\n") ? "\r\n" : "\n"
|
|
134
145
|
header, body = old.split("\n", 2)
|
|
146
|
+
header = header.delete_suffix("\r")
|
|
135
147
|
indent = body.to_s[/\A[ ]+/] || " "
|
|
136
|
-
trailing = body.to_s[
|
|
148
|
+
trailing = body.to_s[/(?:\r?\n)*\z/].to_s
|
|
137
149
|
lines = if entry.node.style == Psych::Nodes::Scalar::FOLDED
|
|
138
150
|
text.split("\n", -1)
|
|
139
151
|
else
|
|
140
152
|
text.chomp.split("\n", -1)
|
|
141
153
|
end
|
|
142
|
-
content = lines.map { it.empty? ? "" : "#{indent}#{it}" }.join(
|
|
143
|
-
"#{header}
|
|
154
|
+
content = lines.map { it.empty? ? "" : "#{indent}#{it}" }.join(eol)
|
|
155
|
+
"#{header}#{eol}#{content}#{trailing}"
|
|
144
156
|
end
|
|
145
157
|
|
|
146
158
|
def check!(updated, locale, key, text, file)
|