samagotchi 0.186.0 → 0.188.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 +68 -1
- data/bin/chi +4 -0
- data/docs/architecture.md +8 -4
- data/docs/bundles.md +124 -120
- data/docs/cli.md +26 -5
- data/docs/configuration.md +4 -4
- data/docs/context.md +18 -162
- data/docs/guardrails.md +3 -1
- data/docs/hooks.md +2 -1
- data/docs/internals/attached-context.md +19 -37
- data/docs/internals/bridge.md +1 -0
- data/docs/internals/engine.md +2 -2
- data/docs/internals/inline-widgets.md +18 -0
- data/docs/internals/llm-context-forget.md +5 -6
- data/docs/internals/objectives.md +1 -0
- data/docs/internals/pages.md +175 -0
- data/docs/internals/peers.md +149 -0
- data/docs/internals/remote-sessions.md +7 -4
- data/docs/internals/web-frontend.md +65 -40
- data/docs/internals/web-push.md +1 -1
- data/docs/memory.md +8 -1
- data/docs/pages.md +151 -0
- data/docs/peers.md +141 -0
- data/docs/plugins.md +52 -27
- data/docs/sessions.md +8 -4
- data/docs/sub-agent.md +5 -5
- data/lib/samagotchi/bridge.rb +3 -3
- data/lib/samagotchi/bundle_command/api_calls.rb +2 -1
- data/lib/samagotchi/bundle_command/check.rb +1 -1
- data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -18
- data/lib/samagotchi/bundles/claude-peer/plugin.rb +22 -16
- data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +48 -39
- data/lib/samagotchi/bundles/claude-peer/scripts/pair +15 -73
- data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +16 -16
- data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -15
- data/lib/samagotchi/bundles/codex-peer/plugin.rb +35 -24
- data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +51 -40
- data/lib/samagotchi/bundles/codex-peer/scripts/pair +18 -54
- data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +16 -16
- data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
- data/lib/samagotchi/bundles/skills/manifest.yml +2 -2
- data/lib/samagotchi/bundles/skills/plugin.rb +14 -8
- data/lib/samagotchi/bundles/system/manifest.yml +5 -2
- data/lib/samagotchi/bundles/system/self_map.md +5 -1
- data/lib/samagotchi/bundles/system/skill_pages.md +93 -0
- data/lib/samagotchi/client_id.rb +15 -1
- data/lib/samagotchi/config.rb +8 -7
- data/lib/samagotchi/context_absorber.rb +23 -277
- data/lib/samagotchi/context_sources.rb +17 -69
- data/lib/samagotchi/engine/messages.rb +12 -1
- data/lib/samagotchi/engine/plugins.rb +1 -1
- data/lib/samagotchi/engine.rb +7 -6
- data/lib/samagotchi/engine_peers.rb +0 -3
- data/lib/samagotchi/guardrail_wiring.rb +2 -0
- data/lib/samagotchi/guardrails/chi_dirs.rb +4 -3
- data/lib/samagotchi/guardrails/parent_approvals.rb +6 -5
- data/lib/samagotchi/guardrails/protected_paths.rb +6 -3
- data/lib/samagotchi/inline_widgets.rb +73 -0
- data/lib/samagotchi/log_line.rb +1 -1
- data/lib/samagotchi/note_move.rb +3 -1
- data/lib/samagotchi/page_command.rb +243 -0
- data/lib/samagotchi/pages/builder.rb +186 -0
- data/lib/samagotchi/pages/launch.rb +193 -0
- data/lib/samagotchi/pages/runner.rb +154 -0
- data/lib/samagotchi/pages/store.rb +152 -0
- data/lib/samagotchi/pages.rb +119 -0
- data/lib/samagotchi/peer_command.rb +192 -0
- data/lib/samagotchi/peer_continue.rb +99 -0
- data/lib/samagotchi/peer_exchanges.rb +3 -3
- data/lib/samagotchi/peer_mailbox.rb +360 -0
- data/lib/samagotchi/peer_note.rb +208 -0
- data/lib/samagotchi/peer_receipts.rb +247 -0
- data/lib/samagotchi/peer_registry.rb +44 -0
- data/lib/samagotchi/peer_roster.rb +79 -0
- data/lib/samagotchi/peer_say.rb +168 -0
- data/lib/samagotchi/plugin/api.rb +29 -21
- data/lib/samagotchi/plugin/context.rb +7 -0
- data/lib/samagotchi/plugin/loader.rb +3 -3
- data/lib/samagotchi/plugin/peer.rb +175 -64
- data/lib/samagotchi/plugin/peers.rb +70 -0
- data/lib/samagotchi/run_options.rb +3 -1
- data/lib/samagotchi/schedule_command.rb +10 -3
- data/lib/samagotchi/schedule_display.rb +32 -0
- data/lib/samagotchi/session_access/contract.rb +19 -2
- data/lib/samagotchi/session_access/local.rb +132 -14
- data/lib/samagotchi/session_access/remote.rb +4 -2
- data/lib/samagotchi/session_access/remote_peers.rb +75 -0
- data/lib/samagotchi/session_continue.rb +12 -0
- data/lib/samagotchi/session_inbox_delivery.rb +5 -2
- data/lib/samagotchi/session_manager/delivery.rb +5 -3
- data/lib/samagotchi/session_manager/removal.rb +2 -0
- data/lib/samagotchi/session_manager/spawn.rb +2 -1
- data/lib/samagotchi/session_manager.rb +1 -0
- data/lib/samagotchi/session_stores.rb +17 -0
- data/lib/samagotchi/steer.rb +1 -1
- data/lib/samagotchi/system_prompt.rb +1 -1
- data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
- data/lib/samagotchi/terminal_ui/formatting.rb +4 -1
- data/lib/samagotchi/testing/boundary.rb +4 -13
- data/lib/samagotchi/testing/bundle.rb +40 -5
- data/lib/samagotchi/testing/install.rb +4 -4
- data/lib/samagotchi/testing/recording_api.rb +2 -1
- data/lib/samagotchi/tools/context_read.rb +0 -14
- data/lib/samagotchi/tools/list_schedules.rb +8 -3
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +7 -18
- data/lib/samagotchi/web/message_display.rb +4 -2
- data/lib/samagotchi/web/page_routes.rb +116 -0
- data/lib/samagotchi/web/peer_routes.rb +133 -0
- data/lib/samagotchi/web/public/app.js +35 -95
- data/lib/samagotchi/web/public/bubbles.js +2 -2
- data/lib/samagotchi/web/public/cards_place.js +20 -1
- data/lib/samagotchi/web/public/context_chips.js +45 -46
- data/lib/samagotchi/web/public/history_reveal.js +4 -1
- data/lib/samagotchi/web/public/history_shape.js +3 -2
- data/lib/samagotchi/web/public/index.html +16 -0
- data/lib/samagotchi/web/public/notify.js +1 -1
- data/lib/samagotchi/web/public/page_blocks.js +58 -0
- data/lib/samagotchi/web/public/page_links.js +33 -0
- data/lib/samagotchi/web/public/page_model.js +68 -0
- data/lib/samagotchi/web/public/page_route.js +24 -0
- data/lib/samagotchi/web/public/page_table.js +74 -0
- data/lib/samagotchi/web/public/page_table_model.js +76 -0
- data/lib/samagotchi/web/public/page_view.js +219 -0
- data/lib/samagotchi/web/public/pages.css +77 -0
- data/lib/samagotchi/web/public/pages_group.js +65 -0
- data/lib/samagotchi/web/public/peer_chip.js +60 -74
- data/lib/samagotchi/web/public/peer_data.js +13 -11
- data/lib/samagotchi/web/public/peer_links.js +12 -7
- data/lib/samagotchi/web/public/peer_mailbox_api.js +20 -0
- data/lib/samagotchi/web/public/peer_note.js +7 -3
- data/lib/samagotchi/web/public/peer_text.js +4 -4
- data/lib/samagotchi/web/public/quiet_notes.js +199 -0
- data/lib/samagotchi/web/public/revise_stack.js +4 -3
- data/lib/samagotchi/web/public/session_view.js +2 -2
- data/lib/samagotchi/web/public/stream_handlers.js +3 -2
- data/lib/samagotchi/web/public/turn_block.js +7 -3
- data/lib/samagotchi/web/public/turn_events.js +6 -0
- data/lib/samagotchi/web/public/views.js +161 -0
- data/lib/samagotchi/web/push/attention.rb +3 -2
- data/lib/samagotchi/web/session_access_routes.rb +3 -20
- data/lib/samagotchi/web/viewer.rb +1 -1
- data/lib/samagotchi/worker/leave.rb +3 -0
- data/lib/samagotchi/worker/mail.rb +73 -0
- data/lib/samagotchi/worker/startup.rb +3 -0
- data/lib/samagotchi/worker/wake_turns.rb +20 -5
- data/lib/samagotchi/worker.rb +12 -6
- data/lib/samagotchi/worker_inbound/mail.rb +214 -0
- data/lib/samagotchi/worker_inbound.rb +43 -46
- data/lib/samagotchi/worker_wakes.rb +26 -21
- metadata +39 -2
- data/lib/samagotchi/peer_sources.rb +0 -58
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require "rbconfig"
|
|
5
|
+
require_relative "../pages"
|
|
6
|
+
require_relative "../child_env"
|
|
7
|
+
require_relative "../process_group"
|
|
8
|
+
require_relative "../agent_caller"
|
|
9
|
+
require_relative "../session_access/dispatch"
|
|
10
|
+
|
|
11
|
+
module Samagotchi
|
|
12
|
+
module Pages
|
|
13
|
+
# One run of a page: the one launch path, for `chi page run` and (Build 2)
|
|
14
|
+
# chi web's Refresh alike. It takes the page's lock, starts the runner
|
|
15
|
+
# (pages/runner.rb) in a process group of its own, in the pages folder,
|
|
16
|
+
# with this process's environment as a worker gets it (the Bundler changes
|
|
17
|
+
# undone, the spawner's keys and #cleared_keys unset, the XDG dirs
|
|
18
|
+
# absolute) and the lock on fd 3 (the runner holds it too, and has a
|
|
19
|
+
# deadline of its own for a launcher that dies mid-run), reads its
|
|
20
|
+
# stdout and stderr through bounded readers, and cuts it at +timeout+.
|
|
21
|
+
# The runner writes the output file; a cut, or a runner that ended without
|
|
22
|
+
# writing one, is recorded here (Store.record_failure). Whatever the
|
|
23
|
+
# script left running in its group is killed after any exit.
|
|
24
|
+
# ContextFetch#run_command is the model.
|
|
25
|
+
module Launch
|
|
26
|
+
# This chi's lib: the runner is started from the same code (a checkout
|
|
27
|
+
# or an installed gem alike).
|
|
28
|
+
LIB_DIR = File.expand_path("../..", __dir__)
|
|
29
|
+
BOOT = 'require "samagotchi/pages/runner"; exit Samagotchi::Pages::Runner.run(ARGV)'
|
|
30
|
+
PIPE_CAP = 64 * 1024
|
|
31
|
+
# How long the group gets after TERM before KILL, and the readers
|
|
32
|
+
# after the exit.
|
|
33
|
+
GRACE_SECONDS = 1.0
|
|
34
|
+
POLL_SECONDS = 0.05
|
|
35
|
+
# The runner's own deadline is the timeout + GRACE_SECONDS + this,
|
|
36
|
+
# from its start: later than the launcher's cut, which wins whenever
|
|
37
|
+
# the launcher is alive.
|
|
38
|
+
DEADLINE_MARGIN = 2.0
|
|
39
|
+
# The fd the runner gets the page's lock on.
|
|
40
|
+
LOCK_FD = 3
|
|
41
|
+
|
|
42
|
+
# +page+ the stored page after the run; +stdout+ / +stderr+ the
|
|
43
|
+
# script's own words (their last 64 KB); +seconds+ the run's wall time.
|
|
44
|
+
Result = Data.define(:ok, :page, :stdout, :stderr, :seconds) do
|
|
45
|
+
def ok? = ok
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
module_function
|
|
49
|
+
|
|
50
|
+
# @param cancelled [#call, nil] polled while the run waits: true stops
|
|
51
|
+
# the run as the cut does, recorded as "the run was stopped" (chi web
|
|
52
|
+
# stopping during a Refresh)
|
|
53
|
+
# @raise [BadName] [Missing] [Busy]
|
|
54
|
+
# @return [Result]
|
|
55
|
+
def run(name, timeout: TIMEOUT_SECONDS, cancelled: nil)
|
|
56
|
+
Pages.check_name!(name)
|
|
57
|
+
raise Missing, name unless File.file?(Pages.script_path(name))
|
|
58
|
+
|
|
59
|
+
Store.locked(name) do |lock|
|
|
60
|
+
# Again under the lock: a `chi page rm` between the check above and
|
|
61
|
+
# the lock removed the page, so this run writes nothing (not even
|
|
62
|
+
# the lock file it just made).
|
|
63
|
+
unless File.file?(Pages.script_path(name))
|
|
64
|
+
FileUtils.rm_f(Store.lock_path(name))
|
|
65
|
+
raise Missing, name
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
launch(name, timeout, lock, cancelled)
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# The runner's argv: the name, the timeout (for its cut's words) and
|
|
73
|
+
# its own deadline in seconds.
|
|
74
|
+
def command(name, timeout)
|
|
75
|
+
[RbConfig.ruby, "-I", LIB_DIR, "-e", BOOT, name, seconds(timeout),
|
|
76
|
+
seconds(timeout + GRACE_SECONDS + DEADLINE_MARGIN)]
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# The changes to this process's env a run gets, as a worker's
|
|
80
|
+
# (SessionManager::WorkerCommand#spawn_options): an installed gem's
|
|
81
|
+
# Bundler changes mapped back, the spawner's keys unset, the XDG dirs
|
|
82
|
+
# absolute. PWD is set to the pages folder too: spawn's chdir doesn't
|
|
83
|
+
# change it, and a script reading ENV["PWD"] would otherwise see the
|
|
84
|
+
# caller's folder, so the terminal and chi web would differ.
|
|
85
|
+
# The remote, worker and agent markers (#cleared_keys) are unset too.
|
|
86
|
+
def env
|
|
87
|
+
ChildEnv.unbundled.merge(ChildEnv.unset).merge(cleared_keys.to_h { |key| [key, nil] })
|
|
88
|
+
.merge(Paths.absolute_xdg).merge("PWD" => Pages.scripts_dir)
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# What a run never takes from its launcher, so the terminal and chi web
|
|
92
|
+
# are one path: CHI_REMOTE (a run never goes remote), a worker's
|
|
93
|
+
# markers (it is no worker's child) and the vendor agent markers (a
|
|
94
|
+
# script's `chi send` is the owner's, even from a chi web started in an
|
|
95
|
+
# agent's pane).
|
|
96
|
+
# @return [Array<String>]
|
|
97
|
+
def cleared_keys(env = ENV)
|
|
98
|
+
[SessionAccess::Dispatch::ENV_KEY, *AgentCaller::VENDOR_MARKERS.map(&:first)] +
|
|
99
|
+
env.each_key.select { |key| key.start_with?(ChildEnv::WORKER_PREFIX) }
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def launch(name, timeout, lock, cancelled)
|
|
103
|
+
before = Store.file_id(name)
|
|
104
|
+
started = monotonic
|
|
105
|
+
out_r, out_w = IO.pipe
|
|
106
|
+
err_r, err_w = IO.pipe
|
|
107
|
+
pid = ProcessGroup.spawn(env, *command(name, timeout), chdir: Pages.scripts_dir, in: File::NULL, out: out_w,
|
|
108
|
+
err: err_w, LOCK_FD => lock)
|
|
109
|
+
out_w.close
|
|
110
|
+
err_w.close
|
|
111
|
+
readers = [out_r, err_r].map { |io| ProcessGroup::PipeReader.new(io, cap: PIPE_CAP, keep: :tail) }
|
|
112
|
+
|
|
113
|
+
status, cut = wait(pid, timeout, cancelled)
|
|
114
|
+
reaped = true
|
|
115
|
+
# A script's background child would hold the pipes open.
|
|
116
|
+
ProcessGroup.signal(pid, "KILL")
|
|
117
|
+
readers.each { |reader| reader.wait(GRACE_SECONDS) || reader.kill }
|
|
118
|
+
stdout, stderr = readers.map { |reader| reader.text(Encoding::UTF_8).scrub }
|
|
119
|
+
ok = record(name, status, cut, timeout, before, stderr)
|
|
120
|
+
Store.remove_temporary_outputs(name)
|
|
121
|
+
Result.new(ok: ok, page: Store.read(name), stdout: stdout, stderr: stderr, seconds: monotonic - started)
|
|
122
|
+
ensure
|
|
123
|
+
# Cut short (Ctrl-C, an exception): the group doesn't get the
|
|
124
|
+
# terminal's SIGINT (pgroup), so stop and reap it here.
|
|
125
|
+
abandon(pid, readers) if pid && !reaped
|
|
126
|
+
[out_r, out_w, err_r, err_w].each { |io| io.close if io && !io.closed? }
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
# @return [Boolean] whether the run was good. A cut or a runner that
|
|
130
|
+
# ended without its result is recorded here; the runner recorded the rest.
|
|
131
|
+
def record(name, status, cut, timeout, before, stderr)
|
|
132
|
+
sha = Store.script_sha(name)
|
|
133
|
+
written = Store.file_id(name)
|
|
134
|
+
fresh = !written.nil? && written != before
|
|
135
|
+
normal_exit = [0, 1].include?(status&.exitstatus)
|
|
136
|
+
return false if fresh && !normal_exit && Store.read(name).state == :failed
|
|
137
|
+
|
|
138
|
+
cut = nil if cut == :timeout && fresh && normal_exit
|
|
139
|
+
if cut
|
|
140
|
+
message = cut == :cancelled ? "the run was stopped" : "the script was stopped after #{seconds(timeout)} s"
|
|
141
|
+
Store.record_failure(name, message: message, line: nil, script_sha: sha)
|
|
142
|
+
return false
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
if !fresh || !normal_exit
|
|
146
|
+
# Not a backtrace frame: a Ruby crash ends stderr with "from …" lines.
|
|
147
|
+
tail = stderr.lines.map(&:strip).reject { |line| line.empty? || line.start_with?("from ") }.last
|
|
148
|
+
Store.record_failure(name, message: ["the runner ended without a result", tail].compact.join(": "), line: nil,
|
|
149
|
+
script_sha: sha)
|
|
150
|
+
return false
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
status.exitstatus.zero? && Store.read(name).state == :ok
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# @return [Array(Process::Status|nil, Symbol|nil)] the status, and
|
|
157
|
+
# why it was cut: :timeout, :cancelled, or nil when it ended itself
|
|
158
|
+
def wait(pid, timeout, cancelled = nil)
|
|
159
|
+
deadline = monotonic + timeout
|
|
160
|
+
loop do
|
|
161
|
+
_, status = Process.wait2(pid, Process::WNOHANG)
|
|
162
|
+
return [status, nil] if status
|
|
163
|
+
return [stop_group(pid), :timeout] if monotonic > deadline
|
|
164
|
+
return [stop_group(pid), :cancelled] if cancelled&.call
|
|
165
|
+
|
|
166
|
+
sleep(POLL_SECONDS)
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# TERM the group, a grace, then KILL; the reap ends the wait.
|
|
171
|
+
# @return [Process::Status, nil]
|
|
172
|
+
def stop_group(pid)
|
|
173
|
+
status = nil
|
|
174
|
+
reaped = -> { status = Process.wait2(pid, Process::WNOHANG)&.last }
|
|
175
|
+
return status if ProcessGroup.stop(pid, grace: GRACE_SECONDS, poll: POLL_SECONDS, stopped: reaped)
|
|
176
|
+
|
|
177
|
+
status || Process.wait2(pid).last
|
|
178
|
+
rescue Errno::ECHILD
|
|
179
|
+
status
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
def abandon(pid, readers)
|
|
183
|
+
stop_group(pid)
|
|
184
|
+
ProcessGroup.signal(pid, "KILL")
|
|
185
|
+
Array(readers).each(&:kill)
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
def seconds(value) = format("%g", value)
|
|
189
|
+
|
|
190
|
+
def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
191
|
+
end
|
|
192
|
+
end
|
|
193
|
+
end
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../pages"
|
|
4
|
+
|
|
5
|
+
module Samagotchi
|
|
6
|
+
module Pages
|
|
7
|
+
# The page runner: the process Launch starts for one run of one page,
|
|
8
|
+
# ruby -I <lib> -e 'require "samagotchi/pages/runner"; exit Samagotchi::Pages::Runner.run(ARGV)' NAME [TIMEOUT DEADLINE]
|
|
9
|
+
# with the page's lock on fd 3. It holds that lock while it lives and,
|
|
10
|
+
# given a DEADLINE (seconds from its start), stops itself and its group
|
|
11
|
+
# there, recording the cut: a launcher killed mid-run (chi web) leaves at
|
|
12
|
+
# most one bounded run, and the page "already running" until it ends.
|
|
13
|
+
# Requiring this file runs nothing. It loads Pages only (no engine, no
|
|
14
|
+
# config, no web, no plugins, no ProcessGroup), so a run is as light as a
|
|
15
|
+
# Ruby script, and a page's surroundings are the same from the terminal
|
|
16
|
+
# and from chi web.
|
|
17
|
+
#
|
|
18
|
+
# The script is loaded with a fresh module as its wrap (Kernel#load), which
|
|
19
|
+
# gives it `page` and keeps its own methods off Object. What the run built,
|
|
20
|
+
# or what it raised, goes to the output file (Store), never to stdout: a
|
|
21
|
+
# `puts` in a script is the script's own. A TERM (Launch's cut) is not
|
|
22
|
+
# rescued: the launcher records the cut itself.
|
|
23
|
+
module Runner
|
|
24
|
+
# The script's `page "Title" do |ui| … end`, once per run.
|
|
25
|
+
class Collector
|
|
26
|
+
attr_reader :builder
|
|
27
|
+
|
|
28
|
+
def dsl
|
|
29
|
+
collector = self
|
|
30
|
+
Module.new do
|
|
31
|
+
define_method(:page) do |title, &block|
|
|
32
|
+
collector.page(title, &block)
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def page(title)
|
|
38
|
+
raise Refused, "a page script calls page once" if @builder
|
|
39
|
+
|
|
40
|
+
@builder = Builder.new(title)
|
|
41
|
+
yield @builder if block_given?
|
|
42
|
+
nil
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# The fd Launch hands the page's lock on (Launch::LOCK_FD).
|
|
47
|
+
LOCK_FD = 3
|
|
48
|
+
|
|
49
|
+
module_function
|
|
50
|
+
|
|
51
|
+
# @param argv [Array<String>] [NAME] or [NAME, TIMEOUT, DEADLINE]
|
|
52
|
+
# @return [Integer] 0 the page ran, 1 the script failed (recorded), 2
|
|
53
|
+
# no such page (nothing recorded: Launch checks this first)
|
|
54
|
+
def run(argv)
|
|
55
|
+
hold_lock
|
|
56
|
+
name, timeout, deadline = argv
|
|
57
|
+
return 2 unless Pages.valid_name?(name) && File.file?(Pages.script_path(name))
|
|
58
|
+
|
|
59
|
+
# The deadline thread and the result's write take this in turn, and
|
|
60
|
+
# the write sets done under it: a run recorded before the deadline
|
|
61
|
+
# fires (an at_exit still going, the exit itself) is never
|
|
62
|
+
# overwritten by the cut.
|
|
63
|
+
recording = Mutex.new
|
|
64
|
+
done = [false]
|
|
65
|
+
arm_deadline(name, timeout, Float(deadline), recording, done) if deadline
|
|
66
|
+
path = Pages.script_path(name)
|
|
67
|
+
sha = Digest::SHA256.file(path).hexdigest
|
|
68
|
+
collector = Collector.new
|
|
69
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
70
|
+
begin
|
|
71
|
+
load(path, collector.dsl)
|
|
72
|
+
raise Refused, "the script never called page" unless collector.builder
|
|
73
|
+
|
|
74
|
+
data = collector.builder.data
|
|
75
|
+
ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
|
|
76
|
+
recording.synchronize do
|
|
77
|
+
Store.record_run(name, title: data["title"], blocks: data["blocks"], duration_ms: ms, script_sha: sha)
|
|
78
|
+
done[0] = true
|
|
79
|
+
end
|
|
80
|
+
0
|
|
81
|
+
# SystemStackError (endless recursion) and NoMemoryError are no
|
|
82
|
+
# StandardError, but a script's own bug all the same.
|
|
83
|
+
rescue StandardError, ScriptError, SystemExit, SystemStackError, NoMemoryError => e
|
|
84
|
+
recording.synchronize do
|
|
85
|
+
Store.record_failure(name, message: message(e, path), line: line(e, path), script_sha: sha)
|
|
86
|
+
done[0] = true
|
|
87
|
+
end
|
|
88
|
+
1
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# The first act: the inherited lock fd is close-on-exec here, so the
|
|
93
|
+
# runner holds the lock alone. A child the script execs, even one that
|
|
94
|
+
# leaves the group (and so outlives the run), never inherits it: it
|
|
95
|
+
# would keep the page "already running" for as long as it lives. A
|
|
96
|
+
# runner started by hand has no lock there: fd 3 is closed (EBADF) or,
|
|
97
|
+
# as Ruby keeps it for itself when nothing is inherited there, refused
|
|
98
|
+
# (ArgumentError, "RubyVM reserves it").
|
|
99
|
+
def hold_lock
|
|
100
|
+
IO.for_fd(LOCK_FD, autoclose: false).close_on_exec = true
|
|
101
|
+
rescue Errno::EBADF, ArgumentError
|
|
102
|
+
nil
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# At +deadline+ seconds from now the cut is recorded (a dead launcher
|
|
106
|
+
# can't), unless the run's own result is already written (+done+), and
|
|
107
|
+
# the runner's whole group is KILLed either way (it leads its group).
|
|
108
|
+
# A Ruby thread: it can't fire while a C extension holds the GVL
|
|
109
|
+
# (docs/internals/pages.md). Plain Process calls, no ProcessGroup, to
|
|
110
|
+
# stay light.
|
|
111
|
+
def arm_deadline(name, timeout, deadline, recording, done)
|
|
112
|
+
Thread.new do
|
|
113
|
+
sleep(deadline)
|
|
114
|
+
recording.lock
|
|
115
|
+
begin
|
|
116
|
+
unless done[0]
|
|
117
|
+
Store.record_failure(name, message: "the script was stopped after #{timeout} s", line: nil,
|
|
118
|
+
script_sha: Store.script_sha(name))
|
|
119
|
+
end
|
|
120
|
+
# Not an ensure: a normal exit kills this thread, and its ensure would KILL the group.
|
|
121
|
+
rescue StandardError # degrade-ok: the KILL matters more than the record (a dead launcher records nothing)
|
|
122
|
+
nil
|
|
123
|
+
end
|
|
124
|
+
Process.kill("KILL", -Process.pid)
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# The error as the page shows it: a syntax error without its leading
|
|
129
|
+
# "path:line:" (its line is #line's), an exit as what it was.
|
|
130
|
+
def message(error, path)
|
|
131
|
+
case error
|
|
132
|
+
when ScriptError then error.message.sub(/\A#{Regexp.escape(path)}:\d+:\s*/, "")
|
|
133
|
+
when SystemExit
|
|
134
|
+
words = error.message == "exit" ? nil : error.message
|
|
135
|
+
words || "the script called exit #{error.status}"
|
|
136
|
+
else error.message
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# The script's line: a syntax error's from its message's first line
|
|
141
|
+
# (the rest differs between Rubies), anything else's from the first
|
|
142
|
+
# backtrace entry inside the script file. nil when neither has one.
|
|
143
|
+
def line(error, path)
|
|
144
|
+
prefix = "#{path}:"
|
|
145
|
+
if error.is_a?(ScriptError)
|
|
146
|
+
found = error.message.lines.first.to_s[/\A#{Regexp.escape(prefix)}(\d+)/, 1]
|
|
147
|
+
return found.to_i if found
|
|
148
|
+
end
|
|
149
|
+
entry = Array(error.backtrace).find { |frame| frame.start_with?(prefix) }
|
|
150
|
+
entry && entry.delete_prefix(prefix)[/\A\d+/]&.to_i
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
end
|
|
154
|
+
end
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require_relative "../pages"
|
|
5
|
+
|
|
6
|
+
module Samagotchi
|
|
7
|
+
module Pages
|
|
8
|
+
# Where pages live: the scripts (<config>/samagotchi/pages/NAME.rb), each
|
|
9
|
+
# one's output (<state>/samagotchi/pages/NAME/output.json) and its lock
|
|
10
|
+
# (<state>/samagotchi/pages/NAME.lock, beside the folder so a remove can
|
|
11
|
+
# delete the folder while holding it). A failed run rewrites only the
|
|
12
|
+
# error: the blocks of the last good run stay. Every path is built after
|
|
13
|
+
# Pages.check_name!.
|
|
14
|
+
module Store
|
|
15
|
+
OUTPUT = "output.json"
|
|
16
|
+
# How much of a failure's message is kept.
|
|
17
|
+
MAX_MESSAGE = 2000
|
|
18
|
+
|
|
19
|
+
module_function
|
|
20
|
+
|
|
21
|
+
def output_dir(name) = File.join(Pages.state_dir, Pages.check_name!(name))
|
|
22
|
+
def output_path(name) = File.join(output_dir(name), OUTPUT)
|
|
23
|
+
def lock_path(name) = File.join(Pages.state_dir, "#{Pages.check_name!(name)}.lock")
|
|
24
|
+
|
|
25
|
+
# @return [String, nil] the sha256 of NAME's script, nil when it has none
|
|
26
|
+
def script_sha(name)
|
|
27
|
+
path = Pages.script_path(name)
|
|
28
|
+
File.file?(path) ? Digest::SHA256.file(path).hexdigest : nil
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# @return [Stored] never ran when the output file is missing or unreadable
|
|
32
|
+
def read(name)
|
|
33
|
+
raw = read_raw(name)
|
|
34
|
+
error = raw["error"]
|
|
35
|
+
error = if error.is_a?(Hash) && error["message"].is_a?(String)
|
|
36
|
+
Failure.new(message: error["message"], line: error["line"].is_a?(Integer) ? error["line"] : nil,
|
|
37
|
+
at: string(error["at"]), script_sha: string(error["script_sha"]))
|
|
38
|
+
end
|
|
39
|
+
ran_at = string(raw["ran_at"])
|
|
40
|
+
Stored.new(name: name, title: string(raw["title"]), blocks: ran_at && raw["blocks"].is_a?(Array) ? raw["blocks"] : [],
|
|
41
|
+
ran_at: ran_at, duration_ms: raw["duration_ms"].is_a?(Numeric) ? raw["duration_ms"] : nil,
|
|
42
|
+
script_sha: string(raw["script_sha"]), error: error, current_sha: script_sha(name))
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# Every script with a valid name, by name; a file whose name breaks
|
|
46
|
+
# the rule is skipped.
|
|
47
|
+
# @return [Array<Stored>]
|
|
48
|
+
def list
|
|
49
|
+
return [] unless File.directory?(Pages.scripts_dir)
|
|
50
|
+
|
|
51
|
+
Dir.children(Pages.scripts_dir).filter_map do |file|
|
|
52
|
+
name = file.delete_suffix(".rb")
|
|
53
|
+
name if file.end_with?(".rb") && Pages.valid_name?(name) && File.file?(File.join(Pages.scripts_dir, file))
|
|
54
|
+
end.sort.map { |name| read(name) }
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# A good run: its blocks replace the last ones and the error is cleared.
|
|
58
|
+
# @raise [Refused] the output is over MAX_OUTPUT_BYTES
|
|
59
|
+
# @return [Stored]
|
|
60
|
+
def record_run(name, title:, blocks:, duration_ms:, script_sha:)
|
|
61
|
+
stored = Stored.new(name: name, title: title, blocks: blocks, ran_at: now, duration_ms: duration_ms,
|
|
62
|
+
script_sha: script_sha, error: nil, current_sha: script_sha)
|
|
63
|
+
json = JSON.generate(stored.to_json_hash)
|
|
64
|
+
if json.bytesize > MAX_OUTPUT_BYTES
|
|
65
|
+
raise Refused, format("the output is %<kb>.1f KB (at most %<max>d KB)", kb: json.bytesize / 1024.0,
|
|
66
|
+
max: MAX_OUTPUT_BYTES / 1024)
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
write(name, json)
|
|
70
|
+
stored
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# A failed run: the error is set; the last good run's blocks stay.
|
|
74
|
+
# The one writer of a failure, for the runner (the script's) and the
|
|
75
|
+
# launcher (a cut, a runner with no result) alike.
|
|
76
|
+
# @return [Stored]
|
|
77
|
+
def record_failure(name, message:, line:, script_sha:)
|
|
78
|
+
# Scrubbed: a message with stray bytes (backtick output) would make
|
|
79
|
+
# JSON.generate raise inside the runner's rescue and lose the error.
|
|
80
|
+
message = Builder.text_of(message)
|
|
81
|
+
message = "#{message[0, MAX_MESSAGE - 1]}…" if message.size > MAX_MESSAGE
|
|
82
|
+
failure = Failure.new(message: message, line: line, at: now, script_sha: script_sha)
|
|
83
|
+
stored = read(name).with(error: failure)
|
|
84
|
+
write(name, JSON.generate(read_raw(name).merge("error" => failure.to_json_hash)))
|
|
85
|
+
stored
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# Runs the block holding NAME's lock (flock, non-blocking), with the
|
|
89
|
+
# lock's io: Launch hands it to the runner, which then holds the lock
|
|
90
|
+
# for as long as it lives (a killed launcher leaves a run that still
|
|
91
|
+
# holds it).
|
|
92
|
+
# @yieldparam lock [File]
|
|
93
|
+
# @raise [Busy] another process holds it
|
|
94
|
+
def locked(name)
|
|
95
|
+
path = lock_path(name)
|
|
96
|
+
FileUtils.mkdir_p(File.dirname(path))
|
|
97
|
+
File.open(path, File::RDWR | File::CREAT, 0o644) do |lock|
|
|
98
|
+
raise Busy, name unless lock.flock(File::LOCK_EX | File::LOCK_NB)
|
|
99
|
+
|
|
100
|
+
yield lock
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# Deletes NAME's script and output folder under its lock, then the lock.
|
|
105
|
+
# @raise [Missing] no script and no output
|
|
106
|
+
# @raise [Busy] it is running
|
|
107
|
+
def remove(name)
|
|
108
|
+
script = Pages.script_path(name)
|
|
109
|
+
raise Missing, name unless File.exist?(script) || File.exist?(output_dir(name))
|
|
110
|
+
|
|
111
|
+
locked(name) do
|
|
112
|
+
FileUtils.rm_f(script)
|
|
113
|
+
FileUtils.rm_rf(output_dir(name))
|
|
114
|
+
FileUtils.rm_f(lock_path(name))
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# The output file's identity (its inode): AtomicFile renames a new file
|
|
119
|
+
# in for every write, so a run that wrote changes it, even within the
|
|
120
|
+
# same second. nil when there is none.
|
|
121
|
+
def file_id(name)
|
|
122
|
+
File.stat(output_path(name)).ino
|
|
123
|
+
rescue SystemCallError
|
|
124
|
+
nil
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
def write(name, json)
|
|
128
|
+
FileUtils.mkdir_p(output_dir(name))
|
|
129
|
+
AtomicFile.write(output_path(name), json)
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def remove_temporary_outputs(name)
|
|
133
|
+
dir = output_dir(name)
|
|
134
|
+
return unless File.directory?(dir)
|
|
135
|
+
|
|
136
|
+
pattern = /\A#{Regexp.escape(OUTPUT)}\.\d+\.[0-9a-f]{8}\.tmp\z/
|
|
137
|
+
Dir.children(dir).grep(pattern).each { |file| FileUtils.rm_f(File.join(dir, file)) }
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
def read_raw(name)
|
|
141
|
+
raw = JSON.parse(File.read(output_path(name), encoding: Encoding::UTF_8))
|
|
142
|
+
raw.is_a?(Hash) ? raw : {}
|
|
143
|
+
rescue JSON::ParserError, SystemCallError, EncodingError
|
|
144
|
+
{}
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def string(value) = value.is_a?(String) ? value : nil
|
|
148
|
+
|
|
149
|
+
def now = Time.now.utc.iso8601
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
end
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "digest"
|
|
5
|
+
require "time"
|
|
6
|
+
require_relative "inline_widgets"
|
|
7
|
+
require_relative "paths"
|
|
8
|
+
require_relative "atomic_file"
|
|
9
|
+
|
|
10
|
+
module Samagotchi
|
|
11
|
+
# Pages: a Ruby script under <config>/samagotchi/pages/NAME.rb says what to
|
|
12
|
+
# show (`page "Title" do |ui| ui.text …; ui.table …; ui.walk … end`); a run
|
|
13
|
+
# stores the blocks it built as JSON under <state>/samagotchi/pages/NAME/,
|
|
14
|
+
# and what shows a page draws from that file (docs/pages.md,
|
|
15
|
+
# docs/internals/pages.md).
|
|
16
|
+
#
|
|
17
|
+
# Light on purpose: the runner (pages/runner.rb) is a process of its own
|
|
18
|
+
# that requires this file only, so nothing here may require the engine, the
|
|
19
|
+
# config, the web, the plugins or the launcher (pages/launch.rb, which
|
|
20
|
+
# spawns the runner and needs ProcessGroup and ChildEnv).
|
|
21
|
+
module Pages
|
|
22
|
+
autoload :Builder, File.expand_path("pages/builder", __dir__)
|
|
23
|
+
autoload :TableBlock, File.expand_path("pages/builder", __dir__)
|
|
24
|
+
autoload :Store, File.expand_path("pages/store", __dir__)
|
|
25
|
+
|
|
26
|
+
# A page's name: lowercase letters, digits and hyphens, a letter or a
|
|
27
|
+
# digit first, at most 40.
|
|
28
|
+
NAME = /\A[a-z0-9][a-z0-9-]{0,39}\z/
|
|
29
|
+
MAX_ROWS = 500
|
|
30
|
+
MAX_COLUMNS = 12
|
|
31
|
+
MAX_CELL = 300
|
|
32
|
+
MAX_BLOCKS = 20
|
|
33
|
+
MAX_TEXT_BYTES = 16 * 1024
|
|
34
|
+
MAX_OUTPUT_BYTES = 256 * 1024
|
|
35
|
+
TIMEOUT_SECONDS = 30
|
|
36
|
+
FORMATS = %i[money count].freeze
|
|
37
|
+
|
|
38
|
+
# Anything that keeps a page from running or from being stored. Each
|
|
39
|
+
# subclass owns its message.
|
|
40
|
+
class Error < StandardError; end
|
|
41
|
+
|
|
42
|
+
# A rule a script broke (a limit, a table's column, page called twice):
|
|
43
|
+
# the run fails with this message.
|
|
44
|
+
class Refused < Error; end
|
|
45
|
+
|
|
46
|
+
# A name that breaks NAME: the command line's fault (exit 2).
|
|
47
|
+
class BadName < Error
|
|
48
|
+
def initialize(name)
|
|
49
|
+
super("#{name.to_s.inspect} isn't a page name (lowercase letters, digits and hyphens, a letter or digit first, at most 40)")
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# No script for the name.
|
|
54
|
+
class Missing < Error
|
|
55
|
+
def initialize(name)
|
|
56
|
+
super("no page #{name}")
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Another run (or a remove) holds the page's lock.
|
|
61
|
+
class Busy < Error
|
|
62
|
+
def initialize(name)
|
|
63
|
+
super("page #{name} is already running")
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# A failed run: what the script raised (or why it was stopped), the
|
|
68
|
+
# script's line when one is known, when, and the sha256 of the script
|
|
69
|
+
# that failed.
|
|
70
|
+
Failure = Data.define(:message, :line, :at, :script_sha) do
|
|
71
|
+
def to_json_hash = { "message" => message, "line" => line, "at" => at, "script_sha" => script_sha }
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# A page as stored (Store.read): the blocks of its last good run (none
|
|
75
|
+
# before one, ran_at nil) and the last failure since, if any.
|
|
76
|
+
# +current_sha+ is the script's sha256 now (nil when the script is gone).
|
|
77
|
+
Stored = Data.define(:name, :title, :blocks, :ran_at, :duration_ms, :script_sha, :error, :current_sha) do
|
|
78
|
+
# :never_ran, :ok or :failed (the last run failed; the good blocks, if
|
|
79
|
+
# any, are still there).
|
|
80
|
+
def state
|
|
81
|
+
return :failed if error
|
|
82
|
+
return :ok if ran_at
|
|
83
|
+
|
|
84
|
+
:never_ran
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Whether the script differs from the one that made the blocks.
|
|
88
|
+
def changed? = !script_sha.nil? && !current_sha.nil? && current_sha != script_sha
|
|
89
|
+
|
|
90
|
+
# The output file's JSON.
|
|
91
|
+
def to_json_hash
|
|
92
|
+
{ "name" => name, "title" => title, "blocks" => blocks, "ran_at" => ran_at, "duration_ms" => duration_ms,
|
|
93
|
+
"script_sha" => script_sha, "error" => error&.to_json_hash }
|
|
94
|
+
end
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
module_function
|
|
98
|
+
|
|
99
|
+
def valid_name?(name) = name.is_a?(String) && NAME.match?(name)
|
|
100
|
+
|
|
101
|
+
# The one check every path goes through before it builds a path.
|
|
102
|
+
# @return [String] +name+
|
|
103
|
+
# @raise [BadName]
|
|
104
|
+
def check_name!(name)
|
|
105
|
+
raise BadName, name unless valid_name?(name)
|
|
106
|
+
|
|
107
|
+
name
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
# @return [String] <config home>/samagotchi/pages (ConfigFile.config_dir
|
|
111
|
+
# lives in config.rb, which loads far more than a runner may)
|
|
112
|
+
def scripts_dir = File.join(Paths.config_home, Paths::APP_DIR, "pages")
|
|
113
|
+
|
|
114
|
+
# @return [String] <state dir>/pages
|
|
115
|
+
def state_dir = File.join(Paths.state_dir, "pages")
|
|
116
|
+
|
|
117
|
+
def script_path(name) = File.join(scripts_dir, "#{check_name!(name)}.rb")
|
|
118
|
+
end
|
|
119
|
+
end
|