samagotchi 0.185.0 → 0.187.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -1
  3. data/bin/chi +2 -0
  4. data/docs/cli.md +1 -0
  5. data/docs/configuration.md +18 -0
  6. data/docs/guardrails.md +13 -0
  7. data/docs/internals/bridge.md +1 -0
  8. data/docs/internals/engine.md +15 -1
  9. data/docs/internals/inline-widgets.md +18 -0
  10. data/docs/internals/pages.md +172 -0
  11. data/docs/internals/prompt-caching.md +14 -0
  12. data/docs/internals/remote-sessions.md +7 -0
  13. data/docs/internals/web-frontend.md +5 -4
  14. data/docs/memory.md +7 -0
  15. data/docs/pages.md +150 -0
  16. data/docs/thin-clients.md +67 -2
  17. data/lib/samagotchi/bridge.rb +1 -1
  18. data/lib/samagotchi/bundles/system/manifest.yml +5 -2
  19. data/lib/samagotchi/bundles/system/self_map.md +5 -1
  20. data/lib/samagotchi/bundles/system/skill_pages.md +93 -0
  21. data/lib/samagotchi/config.rb +3 -1
  22. data/lib/samagotchi/context_absorber.rb +5 -2
  23. data/lib/samagotchi/engine.rb +9 -2
  24. data/lib/samagotchi/inline_widgets.rb +65 -0
  25. data/lib/samagotchi/llm/chat_loop.rb +16 -2
  26. data/lib/samagotchi/page_command.rb +234 -0
  27. data/lib/samagotchi/pages/builder.rb +187 -0
  28. data/lib/samagotchi/pages/launch.rb +187 -0
  29. data/lib/samagotchi/pages/runner.rb +154 -0
  30. data/lib/samagotchi/pages/store.rb +143 -0
  31. data/lib/samagotchi/pages.rb +119 -0
  32. data/lib/samagotchi/plain_reply.rb +75 -0
  33. data/lib/samagotchi/reply_for.rb +254 -0
  34. data/lib/samagotchi/run_options.rb +1 -0
  35. data/lib/samagotchi/session_access/ask.rb +5 -2
  36. data/lib/samagotchi/session_access/contract.rb +1 -1
  37. data/lib/samagotchi/session_access/exchange/token.rb +42 -7
  38. data/lib/samagotchi/session_access/exchange.rb +5 -2
  39. data/lib/samagotchi/session_access/local.rb +4 -2
  40. data/lib/samagotchi/session_access/remote.rb +5 -1
  41. data/lib/samagotchi/session_manager/delivery.rb +36 -6
  42. data/lib/samagotchi/steer.rb +30 -8
  43. data/lib/samagotchi/turn_anchors.rb +65 -17
  44. data/lib/samagotchi/turn_checkpoint.rb +5 -3
  45. data/lib/samagotchi/version.rb +1 -1
  46. data/lib/samagotchi/web/app.rb +6 -6
  47. data/lib/samagotchi/web/ask_routes.rb +62 -17
  48. data/lib/samagotchi/web/page_routes.rb +116 -0
  49. data/lib/samagotchi/web/participant_access.rb +1 -1
  50. data/lib/samagotchi/web/public/app.js +24 -84
  51. data/lib/samagotchi/web/public/index.html +3 -0
  52. data/lib/samagotchi/web/public/page_blocks.js +58 -0
  53. data/lib/samagotchi/web/public/page_links.js +33 -0
  54. data/lib/samagotchi/web/public/page_model.js +68 -0
  55. data/lib/samagotchi/web/public/page_route.js +24 -0
  56. data/lib/samagotchi/web/public/page_table.js +74 -0
  57. data/lib/samagotchi/web/public/page_table_model.js +76 -0
  58. data/lib/samagotchi/web/public/page_view.js +218 -0
  59. data/lib/samagotchi/web/public/pages.css +77 -0
  60. data/lib/samagotchi/web/public/pages_group.js +65 -0
  61. data/lib/samagotchi/web/public/peer_text.js +22 -5
  62. data/lib/samagotchi/web/public/views.js +161 -0
  63. data/lib/samagotchi/web/session_access_routes.rb +30 -2
  64. data/lib/samagotchi/web/session_control.rb +21 -2
  65. data/lib/samagotchi/web/viewer.rb +1 -1
  66. data/lib/samagotchi/worker.rb +2 -1
  67. metadata +23 -1
@@ -0,0 +1,234 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "cli/command"
5
+ require_relative "cli/exit"
6
+ require_relative "cli/flags"
7
+ require_relative "message_time"
8
+ require_relative "pages"
9
+ require_relative "pages/store"
10
+ require_relative "pages/launch"
11
+
12
+ module Samagotchi
13
+ # `chi page`: run, list and remove pages (docs/pages.md). run goes through
14
+ # Pages::Launch, the one launch path chi web's Refresh takes too, and
15
+ # prints what a model needs to check its own work: per block a few lines,
16
+ # a table's labels, first rows and total, formatted as the page shows them.
17
+ class PageCommand
18
+ include CLI::Command
19
+
20
+ USAGE = <<~TEXT
21
+ Usage: chi page <run|list|rm> [options]
22
+ run NAME [--format text|json] run ~/.config/samagotchi/pages/NAME.rb in a process of its own (in the
23
+ pages folder, cut at #{Pages::TIMEOUT_SECONDS} s with what it started), store what it built and print a summary of
24
+ each block (json: the stored page). A failed run keeps the last good result. Exit 1 when the
25
+ script raised, was stopped or broke a limit, when there is no such page or it is already running.
26
+ list [--format text|json] every page: its title, when it last ran or failed (and on which line),
27
+ (never ran), and "changed" when the script changed since the result was made
28
+ rm NAME remove a page: its script and its stored result
29
+ TEXT
30
+
31
+ SUBCOMMANDS = %w[run list rm].freeze
32
+
33
+ FLAGS = {
34
+ "run" => CLI::Flags.new(help: HELP_WORDS) { |f| f.value "--format" },
35
+ "list" => CLI::Flags.new(help: HELP_WORDS) { |f| f.value "--format" },
36
+ "rm" => CLI::Flags.new(help: HELP_WORDS)
37
+ }.freeze
38
+
39
+ # How much of a run's summary each block gets.
40
+ TEXT_LINES = 3
41
+ TEXT_CHARS = 240
42
+ TABLE_ROWS = 3
43
+ STDERR_LINES = 10
44
+ BLANK = "—"
45
+
46
+ def initialize(argv, stdout: $stdout, stderr: $stderr)
47
+ @argv = argv.dup
48
+ @stdout = stdout
49
+ @stderr = stderr
50
+ end
51
+
52
+ # @return [Integer] 0 done, 1 failed (the script, no such page, busy), 2 usage
53
+ def run
54
+ @sub = @argv[0]
55
+ if @sub.nil? || HELP_WORDS.include?(@sub)
56
+ @stdout.puts(USAGE)
57
+ return CLI::Exit::OK
58
+ end
59
+ return usage_error("unknown subcommand #{@sub}") unless SUBCOMMANDS.include?(@sub)
60
+
61
+ parsed = parse_flags(FLAGS.fetch(@sub), @argv[1..])
62
+ return parsed if parsed.is_a?(Integer)
63
+
64
+ send(:"run_#{@sub}", parsed.options, parsed.args)
65
+ rescue Pages::BadName => e
66
+ usage_error(e.message)
67
+ rescue Pages::Missing, Pages::Busy => e
68
+ error_line("#{command_name}: #{e.message}")
69
+ CLI::Exit::FAILED
70
+ rescue Interrupt
71
+ CLI::Exit::INTERRUPTED
72
+ end
73
+
74
+ # The summary's form of a cell: :money as $0.0000, :count as 1.2k / 3.4M,
75
+ # nil as —, anything else as it is.
76
+ def self.cell(value, format)
77
+ return BLANK if value.nil?
78
+ return value.to_s unless value.is_a?(Numeric)
79
+
80
+ case format
81
+ when "money" then Kernel.format("$%.4f", value)
82
+ when "count" then count(value)
83
+ else value.to_s
84
+ end
85
+ end
86
+
87
+ def self.count(value)
88
+ size = value.abs
89
+ return value.to_s if size < 1000
90
+
91
+ text, unit = size < 1_000_000 ? [value / 1000.0, "k"] : [value / 1_000_000.0, "M"]
92
+ "#{Kernel.format("%.1f", text).delete_suffix(".0")}#{unit}"
93
+ end
94
+
95
+ private
96
+
97
+ def command_name = @sub && SUBCOMMANDS.include?(@sub) ? "chi page #{@sub}" : "chi page"
98
+ def usage_on_error = nil
99
+
100
+ def one_name(args)
101
+ return usage_error("give the page's NAME") if args.empty?
102
+ return usage_error("#{@sub} takes one NAME (unexpected #{args[1]})") if args.size > 1
103
+
104
+ Pages.check_name!(args.first)
105
+ end
106
+
107
+ def run_run(options, args)
108
+ format = options[:format]
109
+ refused = format_refusal(format)
110
+ return refused if refused
111
+
112
+ name = one_name(args)
113
+ return name if name.is_a?(Integer)
114
+
115
+ result = Pages::Launch.run(name)
116
+ if format == "json"
117
+ @stdout.puts(JSON.generate(result.page.to_json_hash))
118
+ elsif result.ok?
119
+ print_summary(result)
120
+ else
121
+ print_failure(result)
122
+ end
123
+ result.ok? ? CLI::Exit::OK : CLI::Exit::FAILED
124
+ end
125
+
126
+ def print_summary(result)
127
+ page = result.page
128
+ @stdout.puts(%(page #{page.name}: #{page.title.inspect} (#{Kernel.format("%.1f", result.seconds)} s)))
129
+ page.blocks.each { |block| summary(block).each { |line| @stdout.puts(line) } }
130
+ end
131
+
132
+ def summary(block)
133
+ case block["type"]
134
+ when "text" then text_summary(block["text"].to_s)
135
+ when "table" then table_summary(block)
136
+ when "walk" then [%(- walk: #{block.dig("data", "title").to_s.inspect}, #{Array(block.dig("data", "steps")).size} steps)]
137
+ else ["- #{block["type"]}"]
138
+ end
139
+ end
140
+
141
+ def text_summary(text)
142
+ lines = text.lines.map(&:chomp)
143
+ shown = lines.first(TEXT_LINES).join("\n")
144
+ cut = lines.size > TEXT_LINES || shown.size > TEXT_CHARS
145
+ shown = shown[0, TEXT_CHARS]
146
+ first, *rest = shown.split("\n", -1)
147
+ ["- text: #{first}#{" …" if cut && rest.empty?}", *rest.each_with_index.map do |line, i|
148
+ " #{line}#{" …" if cut && i == rest.size - 1}"
149
+ end]
150
+ end
151
+
152
+ def table_summary(block)
153
+ columns = Array(block["columns"])
154
+ rows = Array(block["rows"])
155
+ dropped = block["dropped"].to_i
156
+ head = "- table, #{rows.size} rows#{" (#{dropped} dropped)" unless dropped.zero?}, columns: " \
157
+ "#{columns.map { |c| c["label"] }.join(", ")}"
158
+ line = ->(cells) { columns.each_with_index.map { |c, i| self.class.cell(cells[i], c["format"]) }.join(" | ") }
159
+ [head, *rows.first(TABLE_ROWS).map { |cells| " #{line.call(cells)}" },
160
+ *(" total: #{line.call(block["total"])}" if block["total"])]
161
+ end
162
+
163
+ def print_failure(result)
164
+ page = result.page
165
+ error = page.error
166
+ @stdout.flush
167
+ @stderr.puts("error: #{"line #{error.line}: " if error&.line}#{error&.message}")
168
+ result.stderr.lines.map(&:chomp).reject(&:empty?).last(STDERR_LINES).each { |line| @stderr.puts(" #{line}") }
169
+ @stderr.puts("the result of #{local(page.ran_at)} is kept") if page.ran_at
170
+ end
171
+
172
+ def run_list(options, args)
173
+ return usage_error("list takes no NAME (unexpected #{args.first})") unless args.empty?
174
+
175
+ format = options[:format]
176
+ refused = format_refusal(format)
177
+ return refused if refused
178
+
179
+ pages = Pages::Store.list
180
+ if format == "json"
181
+ @stdout.puts(JSON.generate(pages.map do |page|
182
+ page.to_json_hash.except("blocks").merge("state" => page.state.to_s, "changed" => page.changed?)
183
+ end))
184
+ elsif pages.empty?
185
+ @stdout.puts("no pages (a page is a script at #{Paths.tilde(Pages.scripts_dir)}/NAME.rb)")
186
+ else
187
+ print_list(pages)
188
+ end
189
+ CLI::Exit::OK
190
+ end
191
+
192
+ def print_list(pages)
193
+ table = pages.map do |page|
194
+ # A control character (a newline, a tab) in a title would break the row.
195
+ title = page.state == :never_ran ? "(never ran)" : page.title.to_s.gsub(/[[:cntrl:]]+/, " ")
196
+ [page.name, title, [status(page), ("changed" if page.changed?)].compact.join(", ")]
197
+ end
198
+ widths = table.transpose.map { |column| column.map(&:length).max }
199
+ table.each do |row|
200
+ @stdout.puts(row.each_with_index.map { |cell, i| i == row.size - 1 ? cell : cell.ljust(widths[i]) }.join(" ").rstrip)
201
+ end
202
+ end
203
+
204
+ def status(page)
205
+ case page.state
206
+ when :ok then "ran #{ago(page.ran_at)}"
207
+ when :failed then "failed #{ago(page.error.at)}#{" (line #{page.error.line})" if page.error.line}"
208
+ else ""
209
+ end
210
+ end
211
+
212
+ def ago(iso)
213
+ seconds = Time.now - Time.iso8601(iso.to_s)
214
+ seconds < 60 ? "#{[seconds.round, 0].max} s ago" : "#{MessageTime.ago(seconds)} ago"
215
+ rescue ArgumentError
216
+ "at #{iso}"
217
+ end
218
+
219
+ def local(iso)
220
+ Time.iso8601(iso.to_s).localtime.strftime("%Y-%m-%d %H:%M")
221
+ rescue ArgumentError
222
+ iso.to_s
223
+ end
224
+
225
+ def run_rm(_options, args)
226
+ name = one_name(args)
227
+ return name if name.is_a?(Integer)
228
+
229
+ Pages::Store.remove(name)
230
+ @stdout.puts("removed page #{name}")
231
+ CLI::Exit::OK
232
+ end
233
+ end
234
+ end
@@ -0,0 +1,187 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../pages"
4
+
5
+ module Samagotchi
6
+ module Pages
7
+ # What a page script's `ui` is: text, table and walk, each adding one
8
+ # block in order. #data is the page as stored (plain Hashes: it is the
9
+ # JSON edge). A rule broken raises Refused naming the block by its place
10
+ # on the page ("table 2: …"), and the run fails with it.
11
+ class Builder
12
+ attr_reader :title
13
+
14
+ def initialize(title)
15
+ @title = Builder.text_of(title).strip
16
+ raise Refused, "page needs a title" if @title.empty?
17
+
18
+ @blocks = []
19
+ end
20
+
21
+ # @return [Hash] {"title" => …, "blocks" => [...]}
22
+ def data = { "title" => @title, "blocks" => @blocks }
23
+
24
+ # A Markdown text block.
25
+ def text(markdown)
26
+ where = place("text")
27
+ text = Builder.text_of(markdown)
28
+ if text.bytesize > MAX_TEXT_BYTES
29
+ raise Refused, "#{where} is #{kb(text.bytesize)} (at most #{MAX_TEXT_BYTES / 1024} KB)"
30
+ end
31
+
32
+ add("type" => "text", "text" => text)
33
+ end
34
+
35
+ # A table of +rows+ (Hashes, string or symbol keys). +columns+ is a
36
+ # Hash key => label (its order kept) or an Array of keys; +format+ key
37
+ # => :money or :count; +key+ the columns a phone shows before a row is
38
+ # opened (default: the first two after the first whose cells are all
39
+ # numbers or nil); +total+ one more row, by column key.
40
+ def table(rows, columns:, format: {}, key: nil, total: nil)
41
+ where = place("table")
42
+ TableBlock.new(where).build(rows, columns: columns, format: format, key: key, total: total).then { |block| add(block) }
43
+ end
44
+
45
+ # A scenario walk: the data a chi-ui walk holds (title, actors, steps),
46
+ # checked by the same schema (InlineWidgets.check).
47
+ def walk(data = nil, **fields)
48
+ where = place("walk")
49
+ result = InlineWidgets.check("walk", data.nil? ? fields : data)
50
+ raise Refused, "#{where}: #{result.error}" unless result.ok?
51
+
52
+ add("type" => "walk", "data" => result.data)
53
+ end
54
+
55
+ # A value as text, scrubbed to valid UTF-8.
56
+ def self.text_of(value)
57
+ text = value.to_s
58
+ text.encoding == Encoding::UTF_8 && text.valid_encoding? ? text : text.dup.force_encoding(Encoding::UTF_8).scrub
59
+ end
60
+
61
+ private
62
+
63
+ # "table 2": the block's type and its place on the page, 1 first. A
64
+ # page past MAX_BLOCKS fails here, before the block is built.
65
+ def place(type)
66
+ count = @blocks.size + 1
67
+ raise Refused, "the page has more than #{MAX_BLOCKS} blocks (#{type} #{count} is one too many)" if count > MAX_BLOCKS
68
+
69
+ "#{type} #{count}"
70
+ end
71
+
72
+ def add(block)
73
+ @blocks << block
74
+ nil
75
+ end
76
+
77
+ def kb(bytes) = format("%.1f KB", bytes / 1024.0)
78
+ end
79
+
80
+ # One table block, as Builder#table describes it.
81
+ class TableBlock
82
+ def initialize(where)
83
+ @where = where
84
+ end
85
+
86
+ def build(rows, columns:, format:, key:, total:)
87
+ keys, labels = columns(columns)
88
+ formats = formats(format, keys)
89
+ rows = rows(rows)
90
+ kept = rows.first(MAX_ROWS).map { |row| keys.map { |k| TableBlock.cell(row[k]) } }
91
+ key_columns = key_columns(key, keys, kept)
92
+ block = { "type" => "table",
93
+ "columns" => keys.each_with_index.map { |k, i| column(k, labels[i], formats[k], key_columns.include?(k)) },
94
+ "rows" => kept }
95
+ block["total"] = total(total, keys) unless total.nil?
96
+ block["dropped"] = [rows.size - MAX_ROWS, 0].max
97
+ block
98
+ end
99
+
100
+ # A cell as stored: a finite number stays a number (a Rational or a
101
+ # BigDecimal as a Float), nil and true/false stay, anything else is its
102
+ # text (NaN and Infinity too: JSON has neither), scrubbed, cut to
103
+ # MAX_CELL characters with an ellipsis.
104
+ def self.cell(value)
105
+ case value
106
+ when nil, true, false, Integer then value
107
+ when Float then value.finite? ? value : value.to_s
108
+ when Numeric then value.to_f.finite? ? value.to_f : value.to_s
109
+ else
110
+ text = Builder.text_of(value)
111
+ text.size > MAX_CELL ? "#{text[0, MAX_CELL - 1]}…" : text
112
+ end
113
+ end
114
+
115
+ private
116
+
117
+ def columns(columns)
118
+ pairs = case columns
119
+ when Hash then columns.map { |k, label| [k.to_s, Builder.text_of(label)] }
120
+ when Array then columns.map { |k| [k.to_s, k.to_s] }
121
+ else raise Refused, "#{@where}: columns: must be a Hash of key => label or a list of keys"
122
+ end
123
+ raise Refused, "#{@where}: columns: is empty" if pairs.empty?
124
+ raise Refused, "#{@where} has #{pairs.size} columns (at most #{MAX_COLUMNS})" if pairs.size > MAX_COLUMNS
125
+
126
+ pairs.transpose
127
+ end
128
+
129
+ def formats(format, keys)
130
+ raise Refused, "#{@where}: format: must be a Hash of column => :money or :count" unless format.is_a?(Hash)
131
+
132
+ format.to_h do |k, value|
133
+ k = k.to_s
134
+ raise Refused, "#{@where}: format names #{k.inspect}, which is no column" unless keys.include?(k)
135
+ unless value.is_a?(Symbol) && FORMATS.include?(value)
136
+ raise Refused, "#{@where}: column #{k.inspect} has format #{value.inspect} (use :money or :count)"
137
+ end
138
+
139
+ [k, value.to_s]
140
+ end
141
+ end
142
+
143
+ # Rows with string keys.
144
+ def rows(rows)
145
+ raise Refused, "#{@where}: rows must be a list of mappings" unless rows.is_a?(Array)
146
+
147
+ rows.each_with_index.map do |row, index|
148
+ raise Refused, "#{@where}: row #{index + 1} isn't a mapping" unless row.is_a?(Hash)
149
+
150
+ row.transform_keys(&:to_s)
151
+ end
152
+ end
153
+
154
+ # The first column always shows on a phone and isn't one of these.
155
+ def key_columns(key, keys, rows)
156
+ if key.nil?
157
+ return keys.each_index.drop(1).select { |i| rows.all? { |row| row[i].nil? || row[i].is_a?(Numeric) } }
158
+ .first(2).map { |i| keys[i] }
159
+ end
160
+
161
+ Array(key).map do |k|
162
+ k = k.to_s
163
+ raise Refused, "#{@where}: key names #{k.inspect}, which is no column" unless keys.include?(k)
164
+
165
+ k
166
+ end - [keys.first]
167
+ end
168
+
169
+ def total(total, keys)
170
+ raise Refused, "#{@where}: total: must be a Hash by column" unless total.is_a?(Hash)
171
+
172
+ total = total.transform_keys(&:to_s)
173
+ extra = total.keys - keys
174
+ raise Refused, "#{@where}: total names #{extra.first.inspect}, which is no column" unless extra.empty?
175
+
176
+ keys.map { |k| TableBlock.cell(total[k]) }
177
+ end
178
+
179
+ def column(key, label, format, key_column)
180
+ column = { "key" => key, "label" => label }
181
+ column["format"] = format if format
182
+ column["key_column"] = true if key_column
183
+ column
184
+ end
185
+ end
186
+ end
187
+ end
@@ -0,0 +1,187 @@
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
+ Result.new(ok: ok, page: Store.read(name), stdout: stdout, stderr: stderr, seconds: monotonic - started)
121
+ ensure
122
+ # Cut short (Ctrl-C, an exception): the group doesn't get the
123
+ # terminal's SIGINT (pgroup), so stop and reap it here.
124
+ abandon(pid, readers) if pid && !reaped
125
+ [out_r, out_w, err_r, err_w].each { |io| io.close if io && !io.closed? }
126
+ end
127
+
128
+ # @return [Boolean] whether the run was good. A cut or a runner that
129
+ # ended without its result is recorded here; the runner recorded the rest.
130
+ def record(name, status, cut, timeout, before, stderr)
131
+ sha = Store.script_sha(name)
132
+ if cut
133
+ message = cut == :cancelled ? "the run was stopped" : "the script was stopped after #{seconds(timeout)} s"
134
+ Store.record_failure(name, message: message, line: nil, script_sha: sha)
135
+ return false
136
+ end
137
+
138
+ written = Store.file_id(name)
139
+ if written.nil? || written == before || ![0, 1].include?(status&.exitstatus)
140
+ # Not a backtrace frame: a Ruby crash ends stderr with "from …" lines.
141
+ tail = stderr.lines.map(&:strip).reject { |line| line.empty? || line.start_with?("from ") }.last
142
+ Store.record_failure(name, message: ["the runner ended without a result", tail].compact.join(": "), line: nil,
143
+ script_sha: sha)
144
+ return false
145
+ end
146
+
147
+ status.exitstatus.zero? && Store.read(name).state == :ok
148
+ end
149
+
150
+ # @return [Array(Process::Status|nil, Symbol|nil)] the status, and
151
+ # why it was cut: :timeout, :cancelled, or nil when it ended itself
152
+ def wait(pid, timeout, cancelled = nil)
153
+ deadline = monotonic + timeout
154
+ loop do
155
+ _, status = Process.wait2(pid, Process::WNOHANG)
156
+ return [status, nil] if status
157
+ return [stop_group(pid), :timeout] if monotonic > deadline
158
+ return [stop_group(pid), :cancelled] if cancelled&.call
159
+
160
+ sleep(POLL_SECONDS)
161
+ end
162
+ end
163
+
164
+ # TERM the group, a grace, then KILL; the reap ends the wait.
165
+ # @return [Process::Status, nil]
166
+ def stop_group(pid)
167
+ status = nil
168
+ reaped = -> { status = Process.wait2(pid, Process::WNOHANG)&.last }
169
+ return status if ProcessGroup.stop(pid, grace: GRACE_SECONDS, poll: POLL_SECONDS, stopped: reaped)
170
+
171
+ status || Process.wait2(pid).last
172
+ rescue Errno::ECHILD
173
+ status
174
+ end
175
+
176
+ def abandon(pid, readers)
177
+ stop_group(pid)
178
+ ProcessGroup.signal(pid, "KILL")
179
+ Array(readers).each(&:kill)
180
+ end
181
+
182
+ def seconds(value) = format("%g", value)
183
+
184
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
185
+ end
186
+ end
187
+ end