samagotchi 0.187.0 → 0.189.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 (184) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +96 -1
  3. data/bin/chi +2 -0
  4. data/docs/architecture.md +13 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +139 -120
  7. data/docs/cli.md +46 -8
  8. data/docs/configuration.md +4 -4
  9. data/docs/context.md +18 -162
  10. data/docs/guardrails.md +6 -3
  11. data/docs/hooks.md +2 -1
  12. data/docs/internals/attached-context.md +19 -37
  13. data/docs/internals/bridge.md +1 -0
  14. data/docs/internals/bundles.md +3 -3
  15. data/docs/internals/engine.md +2 -2
  16. data/docs/internals/llm-context-forget.md +5 -6
  17. data/docs/internals/objectives.md +1 -0
  18. data/docs/internals/pages.md +71 -21
  19. data/docs/internals/peers.md +149 -0
  20. data/docs/internals/remote-sessions.md +7 -4
  21. data/docs/internals/session-lifecycle.md +19 -6
  22. data/docs/internals/web-frontend.md +63 -39
  23. data/docs/internals/web-push.md +12 -6
  24. data/docs/memory.md +1 -1
  25. data/docs/pages.md +70 -16
  26. data/docs/peers.md +144 -0
  27. data/docs/plugins.md +77 -28
  28. data/docs/releasing.md +1 -1
  29. data/docs/scheduling.md +71 -8
  30. data/docs/sessions.md +12 -8
  31. data/docs/sub-agent.md +5 -5
  32. data/docs/testing.md +1 -1
  33. data/lib/samagotchi/bridge.rb +3 -3
  34. data/lib/samagotchi/bundle_command/api_calls.rb +2 -1
  35. data/lib/samagotchi/bundle_command/check.rb +1 -1
  36. data/lib/samagotchi/bundle_manifest.rb +34 -5
  37. data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -18
  38. data/lib/samagotchi/bundles/claude-peer/plugin.rb +22 -16
  39. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +48 -39
  40. data/lib/samagotchi/bundles/claude-peer/scripts/pair +15 -73
  41. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +16 -16
  42. data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -15
  43. data/lib/samagotchi/bundles/codex-peer/plugin.rb +35 -24
  44. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +51 -40
  45. data/lib/samagotchi/bundles/codex-peer/scripts/pair +18 -54
  46. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +16 -16
  47. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  48. data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
  49. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +159 -0
  50. data/lib/samagotchi/bundles/skills/manifest.yml +2 -2
  51. data/lib/samagotchi/bundles/skills/plugin.rb +14 -8
  52. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  53. data/lib/samagotchi/bundles/system/self_map.md +2 -2
  54. data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
  55. data/lib/samagotchi/client_id.rb +15 -1
  56. data/lib/samagotchi/config.rb +8 -7
  57. data/lib/samagotchi/context_absorber.rb +23 -277
  58. data/lib/samagotchi/context_sources.rb +17 -69
  59. data/lib/samagotchi/engine/messages.rb +12 -1
  60. data/lib/samagotchi/engine/plugins.rb +1 -1
  61. data/lib/samagotchi/engine.rb +7 -6
  62. data/lib/samagotchi/engine_peers.rb +0 -3
  63. data/lib/samagotchi/guardrail_wiring.rb +2 -0
  64. data/lib/samagotchi/guardrails/chi_dirs.rb +4 -3
  65. data/lib/samagotchi/guardrails/parent_approvals.rb +6 -5
  66. data/lib/samagotchi/guardrails/protected_paths.rb +6 -3
  67. data/lib/samagotchi/inline_widgets.rb +11 -3
  68. data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
  69. data/lib/samagotchi/log_line.rb +1 -1
  70. data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
  71. data/lib/samagotchi/memory_bundle/builder.rb +1 -0
  72. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  73. data/lib/samagotchi/note_move.rb +3 -1
  74. data/lib/samagotchi/page_command.rb +25 -13
  75. data/lib/samagotchi/pages/builder.rb +7 -8
  76. data/lib/samagotchi/pages/bundled.rb +83 -0
  77. data/lib/samagotchi/pages/launch.rb +22 -4
  78. data/lib/samagotchi/pages/runner.rb +7 -2
  79. data/lib/samagotchi/pages/runtime.rb +83 -0
  80. data/lib/samagotchi/pages/store.rb +29 -7
  81. data/lib/samagotchi/pages.rb +47 -3
  82. data/lib/samagotchi/peer_command.rb +192 -0
  83. data/lib/samagotchi/peer_continue.rb +105 -0
  84. data/lib/samagotchi/peer_exchanges.rb +3 -3
  85. data/lib/samagotchi/peer_mailbox.rb +360 -0
  86. data/lib/samagotchi/peer_note.rb +208 -0
  87. data/lib/samagotchi/peer_receipts.rb +247 -0
  88. data/lib/samagotchi/peer_registry.rb +44 -0
  89. data/lib/samagotchi/peer_roster.rb +79 -0
  90. data/lib/samagotchi/peer_say.rb +168 -0
  91. data/lib/samagotchi/plugin/api.rb +29 -21
  92. data/lib/samagotchi/plugin/context.rb +7 -0
  93. data/lib/samagotchi/plugin/loader.rb +3 -3
  94. data/lib/samagotchi/plugin/peer.rb +175 -64
  95. data/lib/samagotchi/plugin/peers.rb +70 -0
  96. data/lib/samagotchi/run_options.rb +3 -2
  97. data/lib/samagotchi/schedule_command.rb +88 -39
  98. data/lib/samagotchi/schedule_display.rb +101 -0
  99. data/lib/samagotchi/schedules/busy_part.rb +146 -0
  100. data/lib/samagotchi/schedules/edit_part.rb +120 -0
  101. data/lib/samagotchi/schedules/history_part.rb +51 -0
  102. data/lib/samagotchi/schedules/listing_part.rb +52 -0
  103. data/lib/samagotchi/schedules/notices_part.rb +116 -0
  104. data/lib/samagotchi/schedules/protection_part.rb +103 -0
  105. data/lib/samagotchi/schedules/recurrence.rb +103 -0
  106. data/lib/samagotchi/schedules.rb +134 -330
  107. data/lib/samagotchi/session_access/contract.rb +18 -1
  108. data/lib/samagotchi/session_access/local.rb +140 -14
  109. data/lib/samagotchi/session_access/remote.rb +6 -3
  110. data/lib/samagotchi/session_access/remote_peers.rb +75 -0
  111. data/lib/samagotchi/session_chain/delete.rb +7 -5
  112. data/lib/samagotchi/session_continue.rb +12 -0
  113. data/lib/samagotchi/session_inbox_delivery.rb +5 -2
  114. data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
  115. data/lib/samagotchi/session_lifecycle.rb +3 -2
  116. data/lib/samagotchi/session_manager/delivery.rb +5 -3
  117. data/lib/samagotchi/session_manager/removal.rb +18 -9
  118. data/lib/samagotchi/session_manager/spawn.rb +2 -1
  119. data/lib/samagotchi/session_manager.rb +1 -0
  120. data/lib/samagotchi/session_protection.rb +99 -0
  121. data/lib/samagotchi/session_retention.rb +21 -6
  122. data/lib/samagotchi/session_stores.rb +17 -0
  123. data/lib/samagotchi/sessions_command.rb +4 -0
  124. data/lib/samagotchi/steer.rb +1 -1
  125. data/lib/samagotchi/system_prompt.rb +1 -1
  126. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  127. data/lib/samagotchi/terminal_ui/formatting.rb +4 -1
  128. data/lib/samagotchi/testing/boundary.rb +17 -13
  129. data/lib/samagotchi/testing/bundle.rb +40 -5
  130. data/lib/samagotchi/testing/install.rb +4 -4
  131. data/lib/samagotchi/testing/recording_api.rb +2 -1
  132. data/lib/samagotchi/tools/cancel_schedule.rb +5 -2
  133. data/lib/samagotchi/tools/context_read.rb +0 -14
  134. data/lib/samagotchi/tools/list_schedules.rb +8 -3
  135. data/lib/samagotchi/turn_outcome.rb +41 -0
  136. data/lib/samagotchi/version.rb +1 -1
  137. data/lib/samagotchi/web/app.rb +2 -13
  138. data/lib/samagotchi/web/message_display.rb +4 -2
  139. data/lib/samagotchi/web/page_routes.rb +13 -8
  140. data/lib/samagotchi/web/peer_routes.rb +133 -0
  141. data/lib/samagotchi/web/public/app.js +23 -29
  142. data/lib/samagotchi/web/public/bubbles.js +2 -2
  143. data/lib/samagotchi/web/public/cards_place.js +20 -1
  144. data/lib/samagotchi/web/public/context_chips.js +45 -46
  145. data/lib/samagotchi/web/public/history_reveal.js +4 -1
  146. data/lib/samagotchi/web/public/history_shape.js +3 -2
  147. data/lib/samagotchi/web/public/index.html +24 -2
  148. data/lib/samagotchi/web/public/notify.js +1 -1
  149. data/lib/samagotchi/web/public/owner_claim.js +7 -5
  150. data/lib/samagotchi/web/public/page_links.js +1 -1
  151. data/lib/samagotchi/web/public/page_view.js +10 -6
  152. data/lib/samagotchi/web/public/pages.css +9 -2
  153. data/lib/samagotchi/web/public/pages_group.js +21 -19
  154. data/lib/samagotchi/web/public/pages_list.js +73 -0
  155. data/lib/samagotchi/web/public/pages_model.js +54 -0
  156. data/lib/samagotchi/web/public/pages_wiring.js +66 -0
  157. data/lib/samagotchi/web/public/peer_chip.js +60 -74
  158. data/lib/samagotchi/web/public/peer_data.js +13 -11
  159. data/lib/samagotchi/web/public/peer_links.js +12 -7
  160. data/lib/samagotchi/web/public/peer_mailbox_api.js +20 -0
  161. data/lib/samagotchi/web/public/peer_note.js +7 -3
  162. data/lib/samagotchi/web/public/peer_text.js +4 -4
  163. data/lib/samagotchi/web/public/quiet_notes.js +199 -0
  164. data/lib/samagotchi/web/public/revise_stack.js +4 -3
  165. data/lib/samagotchi/web/public/session_view.js +2 -2
  166. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  167. data/lib/samagotchi/web/public/turn_block.js +7 -3
  168. data/lib/samagotchi/web/public/turn_events.js +6 -0
  169. data/lib/samagotchi/web/public/views.js +77 -23
  170. data/lib/samagotchi/web/push/attention.rb +3 -2
  171. data/lib/samagotchi/web/push/notifier.rb +4 -3
  172. data/lib/samagotchi/web/server.rb +3 -1
  173. data/lib/samagotchi/web/session_access_routes.rb +3 -20
  174. data/lib/samagotchi/web/session_hub.rb +64 -19
  175. data/lib/samagotchi/worker/leave.rb +3 -0
  176. data/lib/samagotchi/worker/mail.rb +73 -0
  177. data/lib/samagotchi/worker/startup.rb +3 -0
  178. data/lib/samagotchi/worker/wake_turns.rb +20 -5
  179. data/lib/samagotchi/worker.rb +12 -6
  180. data/lib/samagotchi/worker_inbound/mail.rb +214 -0
  181. data/lib/samagotchi/worker_inbound.rb +43 -46
  182. data/lib/samagotchi/worker_wakes.rb +26 -21
  183. metadata +35 -2
  184. data/lib/samagotchi/peer_sources.rb +0 -58
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require_relative "../pages"
5
+ require_relative "../installed_bundles"
6
+ require_relative "../log"
7
+
8
+ module Samagotchi
9
+ module Pages
10
+ # The pages installed bundles ship: a manifest's pages: names scripts/
11
+ # files, each NAME.rb the page NAME (docs/pages.md, "Pages from a
12
+ # bundle"). Read from the install records (InstalledBundles), so chi web
13
+ # answers without loading a plugin. The first bundle by name wins a page
14
+ # name; a bundle chi won't use (its record doesn't read, or it needs a
15
+ # newer chi) ships none. The user's own NAME.rb shadows a bundle's page
16
+ # (Pages.script_path), which is how a page is made one's own: copy the
17
+ # bundle's script there and change it.
18
+ #
19
+ # Loaded only when no NAME.rb of the user's is there (Pages autoloads
20
+ # it): installed_bundles.rb reaches the config, which a user's page run
21
+ # never loads.
22
+ module Bundled
23
+ # One bundle page: its name, the bundle, the scripts/ file and its
24
+ # installed path.
25
+ Page = Data.define(:name, :bundle, :file, :path) do
26
+ # Why chi won't run it (its file is missing, unrecorded, or not as
27
+ # installed: InstalledBundles::Dir#file_refusal's words), nil when it may.
28
+ # @return [String, nil]
29
+ def refusal
30
+ recorded = InstalledBundles.standing(bundle)&.record&.scripts&.fetch(file, nil)
31
+ InstalledBundles::Dir.new(name: bundle).file_refusal(:scripts, file, recorded)&.text
32
+ end
33
+ end
34
+
35
+ # What .unread has logged in this process: [bundle, why] pairs.
36
+ WARNED = Set.new
37
+ WARNED_LOCK = Mutex.new
38
+
39
+ module_function
40
+
41
+ # @return [Array<Page>] by name
42
+ def all
43
+ taken = {}
44
+ InstalledBundles.standings do |standing|
45
+ next unless standing.usable?
46
+
47
+ unread(standing.name, standing.record)
48
+ scripts_dir = InstalledBundles::Dir.new(name: standing.name).scripts_dir
49
+ standing.record.manifest.pages.each do |file|
50
+ name = file.delete_suffix(".rb")
51
+ taken[name] ||= Page.new(name: name, bundle: standing.name, file: file, path: File.join(scripts_dir, file))
52
+ end
53
+ end
54
+ taken.values.sort_by(&:name)
55
+ end
56
+
57
+ # @return [Page, nil]
58
+ def find(name) = all.find { |page| page.name == name }
59
+
60
+ # pages: is read from the kept manifest.yml only (never mirrored in the
61
+ # record): a kept file that is edited, stale or missing, or a pages:
62
+ # that doesn't parse, ships no page. Said once per process per bundle
63
+ # and why, when the kept file (as far as it reads) names pages.
64
+ def unread(bundle, record)
65
+ manifest = record.manifest
66
+ why = manifest.problems["pages"] || (manifest.standing && names_pages?(record.kept_manifest_path) && manifest.standing.to_s)
67
+ return unless why && WARNED_LOCK.synchronize { WARNED.add?([bundle, why]) }
68
+
69
+ Log.warn(:web, "bundle_pages_unread", bundle: bundle, why: why,
70
+ msg: "its kept manifest.yml isn't as installed: reinstall the bundle for its pages")
71
+ end
72
+
73
+ def names_pages?(path)
74
+ path && File.file?(path) && YAML.safe_load_file(path).then { |raw| raw.is_a?(Hash) && raw.key?("pages") }
75
+ rescue StandardError # degrade-ok: a kept file that does not read names no pages (the standing already says why)
76
+ false
77
+ end
78
+
79
+ # Forget what was logged (specs).
80
+ def reset_warnings! = WARNED_LOCK.synchronize { WARNED.clear }
81
+ end
82
+ end
83
+ end
@@ -54,21 +54,31 @@ module Samagotchi
54
54
  # @return [Result]
55
55
  def run(name, timeout: TIMEOUT_SECONDS, cancelled: nil)
56
56
  Pages.check_name!(name)
57
- raise Missing, name unless File.file?(Pages.script_path(name))
57
+ raise Missing, name unless Pages.exists?(name)
58
58
 
59
59
  Store.locked(name) do |lock|
60
60
  # Again under the lock: a `chi page rm` between the check above and
61
61
  # the lock removed the page, so this run writes nothing (not even
62
62
  # the lock file it just made).
63
- unless File.file?(Pages.script_path(name))
63
+ unless Pages.exists?(name)
64
64
  FileUtils.rm_f(Store.lock_path(name))
65
65
  raise Missing, name
66
66
  end
67
+ refusal = Pages.bundled(name)&.refusal
68
+ next refused(name, refusal) if refusal
67
69
 
68
70
  launch(name, timeout, lock, cancelled)
69
71
  end
70
72
  end
71
73
 
74
+ # A bundle page whose script isn't as installed runs nothing: the run
75
+ # fails with the refusal's words (Bundled::Page#refusal), the last good
76
+ # result kept, as any failed run.
77
+ def refused(name, refusal)
78
+ Store.record_failure(name, message: refusal, line: nil, script_sha: Store.script_sha(name))
79
+ Result.new(ok: false, page: Store.read(name), stdout: "", stderr: "", seconds: 0.0)
80
+ end
81
+
72
82
  # The runner's argv: the name, the timeout (for its cut's words) and
73
83
  # its own deadline in seconds.
74
84
  def command(name, timeout)
@@ -101,6 +111,8 @@ module Samagotchi
101
111
 
102
112
  def launch(name, timeout, lock, cancelled)
103
113
  before = Store.file_id(name)
114
+ # A bundle's page runs there too: the folder may not exist yet.
115
+ FileUtils.mkdir_p(Pages.scripts_dir)
104
116
  started = monotonic
105
117
  out_r, out_w = IO.pipe
106
118
  err_r, err_w = IO.pipe
@@ -117,6 +129,7 @@ module Samagotchi
117
129
  readers.each { |reader| reader.wait(GRACE_SECONDS) || reader.kill }
118
130
  stdout, stderr = readers.map { |reader| reader.text(Encoding::UTF_8).scrub }
119
131
  ok = record(name, status, cut, timeout, before, stderr)
132
+ Store.remove_temporary_outputs(name)
120
133
  Result.new(ok: ok, page: Store.read(name), stdout: stdout, stderr: stderr, seconds: monotonic - started)
121
134
  ensure
122
135
  # Cut short (Ctrl-C, an exception): the group doesn't get the
@@ -129,14 +142,19 @@ module Samagotchi
129
142
  # ended without its result is recorded here; the runner recorded the rest.
130
143
  def record(name, status, cut, timeout, before, stderr)
131
144
  sha = Store.script_sha(name)
145
+ written = Store.file_id(name)
146
+ fresh = !written.nil? && written != before
147
+ normal_exit = [0, 1].include?(status&.exitstatus)
148
+ return false if fresh && !normal_exit && Store.read(name).state == :failed
149
+
150
+ cut = nil if cut == :timeout && fresh && normal_exit
132
151
  if cut
133
152
  message = cut == :cancelled ? "the run was stopped" : "the script was stopped after #{seconds(timeout)} s"
134
153
  Store.record_failure(name, message: message, line: nil, script_sha: sha)
135
154
  return false
136
155
  end
137
156
 
138
- written = Store.file_id(name)
139
- if written.nil? || written == before || ![0, 1].include?(status&.exitstatus)
157
+ if !fresh || !normal_exit
140
158
  # Not a backtrace frame: a Ruby crash ends stderr with "from …" lines.
141
159
  tail = stderr.lines.map(&:strip).reject { |line| line.empty? || line.start_with?("from ") }.last
142
160
  Store.record_failure(name, message: ["the runner ended without a result", tail].compact.join(": "), line: nil,
@@ -16,12 +16,14 @@ module Samagotchi
16
16
  # and from chi web.
17
17
  #
18
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,
19
+ # gives it `page` and `runtime` and keeps its own methods off Object. What the run built,
20
20
  # or what it raised, goes to the output file (Store), never to stdout: a
21
21
  # `puts` in a script is the script's own. A TERM (Launch's cut) is not
22
22
  # rescued: the launcher records the cut itself.
23
23
  module Runner
24
- # The script's `page "Title" do |ui| … end`, once per run.
24
+ # The script's `page "Title" do |ui| … end`, once per run, and its
25
+ # `runtime` (Pages::Runtime, made on first use: a page that never asks
26
+ # loads none of it).
25
27
  class Collector
26
28
  attr_reader :builder
27
29
 
@@ -31,9 +33,12 @@ module Samagotchi
31
33
  define_method(:page) do |title, &block|
32
34
  collector.page(title, &block)
33
35
  end
36
+ define_method(:runtime) { collector.runtime }
34
37
  end
35
38
  end
36
39
 
40
+ def runtime = @runtime ||= Runtime.new
41
+
37
42
  def page(title)
38
43
  raise Refused, "a page script calls page once" if @builder
39
44
 
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../pages"
4
+
5
+ module Samagotchi
6
+ module Pages
7
+ # What a page script reads of chi itself: `runtime` in a script
8
+ # (Runner::Collector#dsl), one per run (docs/pages.md, "Reading chi's
9
+ # data"). Each method reads in this process, from this chi's code: no
10
+ # `chi` on PATH, no second boot, read-only. Each requires what it reads
11
+ # only when called, so a page that never calls it stays as light as the
12
+ # runner (spec/pages_runtime_spec.rb loads one to check).
13
+ #
14
+ # runtime.schedules every durable schedule (ScheduleList)
15
+ #
16
+ # A method comes with its first page (docs/internals/pages.md).
17
+ class Runtime
18
+ # What a runtime read can't give: the run fails with its message.
19
+ class Unreadable < Error; end
20
+
21
+ # One row of a schedule's history (Schedules::HistoryPart): when, what
22
+ # (fired, skipped, failed, missed, enabled, disabled, edited), why, and
23
+ # the session it acted on. Times are ISO 8601 UTC strings.
24
+ Run = Data.define(:at, :status, :detail, :session_id)
25
+
26
+ # The members a Schedule has: the keys of `chi schedule list --format
27
+ # json` (ScheduleDisplay.json) a page may rely on. The others (a
28
+ # firing's token, its pending turn, extra keys) are chi's bookkeeping.
29
+ SCHEDULE_MEMBERS = %i[id name title mode prompt recurrence_words next_due last_fired last_result enabled state
30
+ off_reason skips max_skips failures max_failures skip_window anchor head created_at
31
+ history].freeze
32
+
33
+ # One schedule as `chi schedule list --format json` says it: +name+ is
34
+ # its title or the start of its prompt in quotes, +state+ "on",
35
+ # "firing" or "off", +off_reason+ why it is off (ScheduleDisplay.off_reason:
36
+ # "owner", "skips", "failures", "done", "missed", "off"; nil when it
37
+ # isn't), +history+ its Runs, oldest first. Times are ISO 8601 UTC
38
+ # strings, nil when there is none.
39
+ Schedule = Data.define(*SCHEDULE_MEMBERS) do
40
+ # @param json [Hash{String => Object}] ScheduleDisplay.json's; a
41
+ # missing key reads as nil (history as none), an unknown one is
42
+ # dropped
43
+ def self.from_json(json)
44
+ fields = SCHEDULE_MEMBERS.to_h { |member| [member, json[member.to_s]] }
45
+ fields[:history] = Array(json["history"]).filter_map do |row|
46
+ row = row.transform_keys(&:to_s) if row.is_a?(Hash)
47
+ row.is_a?(Hash) ? Run.new(at: row["at"], status: row["status"], detail: row["detail"], session_id: row["session_id"]) : nil
48
+ end
49
+ new(**fields)
50
+ end
51
+
52
+ # The schedule as a table row (ui.table): every member but history,
53
+ # string keys.
54
+ def row = to_h.except(:history).transform_keys(&:to_s)
55
+ end
56
+
57
+ # Every schedule (+entries+, Schedules, the earliest due first),
58
+ # Schedules#tick_warning's text when nothing ticks (+warning+, else
59
+ # nil), and the id of each entry schedules.json holds that doesn't read
60
+ # (+unreadable_ids+, nil for one with no id).
61
+ ScheduleList = Data.define(:entries, :warning, :unreadable_ids) do
62
+ include Enumerable
63
+
64
+ def each(&) = entries.each(&)
65
+
66
+ # Every schedule as a table row: `ui.table runtime.schedules.rows, columns: …`.
67
+ def rows = entries.map(&:row)
68
+ end
69
+
70
+ # @return [ScheduleList]
71
+ # @raise [Unreadable] schedules.json isn't readable JSON (Schedules::Corrupt's words)
72
+ def schedules
73
+ require_relative "../schedules"
74
+ require_relative "../schedule_display"
75
+ listing = Schedules.new.listing
76
+ ScheduleList.new(entries: listing.entries.map { |entry| Schedule.from_json(ScheduleDisplay.json(entry)) },
77
+ warning: listing.warning, unreadable_ids: listing.unreadable_ids)
78
+ rescue Schedules::Corrupt => e
79
+ raise Unreadable, e.message
80
+ end
81
+ end
82
+ end
83
+ end
@@ -37,21 +37,28 @@ module Samagotchi
37
37
  at: string(error["at"]), script_sha: string(error["script_sha"]))
38
38
  end
39
39
  ran_at = string(raw["ran_at"])
40
+ bundled = Pages.bundled(name)
40
41
  Stored.new(name: name, title: string(raw["title"]), blocks: ran_at && raw["blocks"].is_a?(Array) ? raw["blocks"] : [],
41
42
  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
+ script_sha: string(raw["script_sha"]), error: error, current_sha: script_sha(name),
44
+ bundle: bundled&.bundle, script: bundled ? bundled.path : Pages.user_script_path(name))
43
45
  end
44
46
 
45
- # Every script with a valid name, by name; a file whose name breaks
46
- # the rule is skipped.
47
+ # Every page by name: each script with a valid name in the pages
48
+ # folder (a file whose name breaks the rule is skipped) and each page
49
+ # an installed bundle ships (Bundled), one per name.
47
50
  # @return [Array<Stored>]
48
51
  def list
52
+ (user_names | Pages::Bundled.all.map(&:name)).sort.map { |name| read(name) }
53
+ end
54
+
55
+ def user_names
49
56
  return [] unless File.directory?(Pages.scripts_dir)
50
57
 
51
58
  Dir.children(Pages.scripts_dir).filter_map do |file|
52
59
  name = file.delete_suffix(".rb")
53
60
  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) }
61
+ end
55
62
  end
56
63
 
57
64
  # A good run: its blocks replace the last ones and the error is cleared.
@@ -79,8 +86,9 @@ module Samagotchi
79
86
  # JSON.generate raise inside the runner's rescue and lose the error.
80
87
  message = Builder.text_of(message)
81
88
  message = "#{message[0, MAX_MESSAGE - 1]}…" if message.size > MAX_MESSAGE
82
- stored = read(name).with(error: Failure.new(message: message, line: line, at: now, script_sha: script_sha))
83
- write(name, JSON.generate(stored.to_json_hash))
89
+ failure = Failure.new(message: message, line: line, at: now, script_sha: script_sha)
90
+ stored = read(name).with(error: failure)
91
+ write(name, JSON.generate(read_raw(name).merge("error" => failure.to_json_hash)))
84
92
  stored
85
93
  end
86
94
 
@@ -101,10 +109,16 @@ module Samagotchi
101
109
  end
102
110
 
103
111
  # Deletes NAME's script and output folder under its lock, then the lock.
112
+ # Only the user's own script (Pages.user_script_path), never a
113
+ # bundle's: with the user's NAME.rb gone, a bundle page it shadowed is
114
+ # back, as never ran.
115
+ # @raise [FromBundle] NAME is a bundle's page (no NAME.rb of the user's)
104
116
  # @raise [Missing] no script and no output
105
117
  # @raise [Busy] it is running
106
118
  def remove(name)
107
- script = Pages.script_path(name)
119
+ script = Pages.user_script_path(name)
120
+ bundled = Pages.bundled(name)
121
+ raise FromBundle.new(name, bundled.bundle) if bundled
108
122
  raise Missing, name unless File.exist?(script) || File.exist?(output_dir(name))
109
123
 
110
124
  locked(name) do
@@ -128,6 +142,14 @@ module Samagotchi
128
142
  AtomicFile.write(output_path(name), json)
129
143
  end
130
144
 
145
+ def remove_temporary_outputs(name)
146
+ dir = output_dir(name)
147
+ return unless File.directory?(dir)
148
+
149
+ pattern = /\A#{Regexp.escape(OUTPUT)}\.\d+\.[0-9a-f]{8}\.tmp\z/
150
+ Dir.children(dir).grep(pattern).each { |file| FileUtils.rm_f(File.join(dir, file)) }
151
+ end
152
+
131
153
  def read_raw(name)
132
154
  raw = JSON.parse(File.read(output_path(name), encoding: Encoding::UTF_8))
133
155
  raw.is_a?(Hash) ? raw : {}
@@ -17,11 +17,15 @@ module Samagotchi
17
17
  # Light on purpose: the runner (pages/runner.rb) is a process of its own
18
18
  # that requires this file only, so nothing here may require the engine, the
19
19
  # config, the web, the plugins or the launcher (pages/launch.rb, which
20
- # spawns the runner and needs ProcessGroup and ChildEnv).
20
+ # spawns the runner and needs ProcessGroup and ChildEnv). What a script
21
+ # reads of chi (Pages::Runtime) requires its own code when called, never
22
+ # at load (spec/pages_runtime_spec.rb runs a page to check).
21
23
  module Pages
22
24
  autoload :Builder, File.expand_path("pages/builder", __dir__)
23
25
  autoload :TableBlock, File.expand_path("pages/builder", __dir__)
24
26
  autoload :Store, File.expand_path("pages/store", __dir__)
27
+ autoload :Runtime, File.expand_path("pages/runtime", __dir__)
28
+ autoload :Bundled, File.expand_path("pages/bundled", __dir__)
25
29
 
26
30
  # A page's name: lowercase letters, digits and hyphens, a letter or a
27
31
  # digit first, at most 40.
@@ -57,6 +61,15 @@ module Samagotchi
57
61
  end
58
62
  end
59
63
 
64
+ # A remove of a page a bundle ships (Bundled): its script is the
65
+ # bundle's, and the page lasts as long as the bundle does.
66
+ class FromBundle < Error
67
+ def initialize(name, bundle)
68
+ super("page #{name} comes with the #{bundle} bundle: uninstall the bundle or write your own " \
69
+ "#{Paths.tilde(Pages.user_script_path(name))}")
70
+ end
71
+ end
72
+
60
73
  # Another run (or a remove) holds the page's lock.
61
74
  class Busy < Error
62
75
  def initialize(name)
@@ -74,7 +87,12 @@ module Samagotchi
74
87
  # A page as stored (Store.read): the blocks of its last good run (none
75
88
  # before one, ran_at nil) and the last failure since, if any.
76
89
  # +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
90
+ # +bundle+ the bundle whose script it runs (Bundled), nil for the
91
+ # user's own; +script+ the script's path (Pages.script_path).
92
+ Stored = Data.define(:name, :title, :blocks, :ran_at, :duration_ms, :script_sha, :error, :current_sha, :bundle,
93
+ :script) do
94
+ def initialize(bundle: nil, script: nil, **fields) = super
95
+
78
96
  # :never_ran, :ok or :failed (the last run failed; the good blocks, if
79
97
  # any, are still there).
80
98
  def state
@@ -114,6 +132,32 @@ module Samagotchi
114
132
  # @return [String] <state dir>/pages
115
133
  def state_dir = File.join(Paths.state_dir, "pages")
116
134
 
117
- def script_path(name) = File.join(scripts_dir, "#{check_name!(name)}.rb")
135
+ # Where the user's own NAME.rb is (or would be): what a remove deletes.
136
+ def user_script_path(name) = File.join(scripts_dir, "#{check_name!(name)}.rb")
137
+
138
+ # The script NAME runs: the user's NAME.rb when there is one, else the
139
+ # page of that name an installed bundle ships (Bundled), else the user's
140
+ # path (no such page). Every read and run resolves here; a remove never
141
+ # does (user_script_path).
142
+ def script_path(name)
143
+ user = user_script_path(name)
144
+ return user if File.file?(user)
145
+
146
+ Bundled.find(name)&.path || user
147
+ end
148
+
149
+ # Whether NAME is a page: a script of the user's, or a bundle's page,
150
+ # even one whose installed script is gone (its run then fails with the
151
+ # bundle's refusal, Bundled::Page#refusal, rather than "no page").
152
+ def exists?(name) = File.file?(script_path(name)) || !bundled(name).nil?
153
+
154
+ # The bundle page NAME runs, nil when the user's NAME.rb shadows it or no
155
+ # bundle ships one.
156
+ # @return [Bundled::Page, nil]
157
+ def bundled(name)
158
+ return nil if File.file?(user_script_path(name))
159
+
160
+ Bundled.find(name)
161
+ end
118
162
  end
119
163
  end
@@ -0,0 +1,192 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "peer_mailbox"
5
+ require_relative "peer_say"
6
+ require_relative "peer_roster"
7
+ require_relative "session"
8
+ require_relative "cli/command"
9
+ require_relative "cli/exit"
10
+ require_relative "cli/flags"
11
+ require_relative "session_access/local"
12
+
13
+ module Samagotchi
14
+ # `chi peer`: a peer agent's side of a session (PeerMailbox). The pair
15
+ # scripts run pair; the peer's skill runs say for every message and quotes
16
+ # the line it prints (what chi did with it, PeerSay); ls is what the owner
17
+ # or the peer looks at. Through --remote the remote's chi web does the
18
+ # same (SessionAccess::Remote).
19
+ class PeerCommand
20
+ include CLI::Command
21
+
22
+ USAGE = <<~TEXT
23
+ Usage: chi peer <pair|unpair|say|ls> [options]
24
+ pair NAME ID [--address ADDR] [--from TEXT] pair peer NAME with session ID
25
+ --address: where chi's sends go (none: it only answers); --from: who paired
26
+ unpair NAME ID end the pairing (its messages stay)
27
+ say NAME ID (--wake|--nowake) [--summary TEXT] [--re REF] [-m TEXT] [--wait SECONDS]
28
+ a message from NAME (stdin without -m); prints what chi did with it.
29
+ --wake: chi may run a turn for it; --re: the send it answers;
30
+ --wait: how long to wait for chi's answer (0 to #{PeerSay::WAIT_MAX}, default 0)
31
+ ls ID [--format json] the session's peers, their messages and receipts
32
+ NAME: the peer (claude, codex): a lowercase letter, then lowercase letters and digits.
33
+ ID: a session id or unique prefix. Find ids with: chi sessions list [--live]
34
+ TEXT
35
+
36
+ SUBCOMMANDS = %w[pair unpair say ls].freeze
37
+
38
+ FLAGS = {
39
+ "pair" => CLI::Flags.new(help: HELP_WORDS) do |f|
40
+ f.value "--address"
41
+ f.value "--from"
42
+ end,
43
+ "unpair" => CLI::Flags.new(help: HELP_WORDS),
44
+ "say" => CLI::Flags.new(help: HELP_WORDS) do |f|
45
+ f.switch "--wake"
46
+ f.switch "--nowake", key: :wake, set: false
47
+ f.value "--summary"
48
+ f.value "--re"
49
+ f.value "-m", "--message", key: :text
50
+ f.value "--wait"
51
+ end,
52
+ "ls" => CLI::Flags.new(help: HELP_WORDS) { |f| f.value "--format" }
53
+ }.freeze
54
+
55
+ # @param argv [Array<String>] the arguments after "peer"
56
+ # @param access [SessionAccess::Local, SessionAccess::Remote, nil] where
57
+ # the sessions are; default this machine's, in +state_dir+
58
+ # @param sleeper [#call, nil] a say's wait between two looks (specs)
59
+ def initialize(argv, stdin: $stdin, stdout: $stdout, stderr: $stderr, state_dir: nil, access: nil, sleeper: nil)
60
+ @argv = argv.dup
61
+ @stdin = stdin
62
+ @stdout = stdout
63
+ @stderr = stderr
64
+ @state_dir = state_dir || Session.default_state_dir
65
+ @access = access || SessionAccess::Local.new(state_dir: @state_dir)
66
+ @sleeper = sleeper
67
+ end
68
+
69
+ # @return [Integer] exit status: 0 done, 1 refused or failed, 2 usage
70
+ def run
71
+ @sub = @argv[0]
72
+ if @sub.nil? || HELP_WORDS.include?(@sub)
73
+ @stdout.puts(USAGE)
74
+ return 0
75
+ end
76
+ return usage_error("unknown subcommand #{@sub}") unless SUBCOMMANDS.include?(@sub)
77
+
78
+ parsed = parse_flags(FLAGS.fetch(@sub), @argv[1..])
79
+ return parsed if parsed.is_a?(Integer)
80
+
81
+ send(:"run_#{@sub}", parsed.options, parsed.args)
82
+ rescue PeerMailbox::Invalid => e
83
+ error_line("#{command_name}: #{e.message}")
84
+ CLI::Exit::FAILED
85
+ rescue ArgumentError, SessionAccess::RemoteFailed => e
86
+ error_line("#{command_name}: #{e.message}")
87
+ CLI::Exit::FAILED
88
+ end
89
+
90
+ private
91
+
92
+ def command_name = @sub && SUBCOMMANDS.include?(@sub) ? "chi peer #{@sub}" : "chi peer"
93
+
94
+ # NAME and ID, checked: [name, id], or the exit status.
95
+ def name_and_id(args)
96
+ return usage_error("give the peer's NAME and the session ID") unless args.size == 2
97
+
98
+ name, given = args
99
+ return usage_error(PeerMailbox.name_problem(name)) unless PeerMailbox.valid_name?(name)
100
+
101
+ [name, @access.resolve_id(given)]
102
+ end
103
+
104
+ def run_pair(options, args)
105
+ checked = name_and_id(args)
106
+ return checked if checked.is_a?(Integer)
107
+
108
+ name, id = checked
109
+ paired = @access.peer_pair(id, name, address: options[:address], from: options[:from])
110
+ unless paired.status == :paired
111
+ error_line("#{command_name}: #{paired.refusal}")
112
+ return CLI::Exit::FAILED
113
+ end
114
+
115
+ @stdout.puts("#{id[0, 8]} paired with #{PeerMailbox.label(name)}")
116
+ 0
117
+ end
118
+
119
+ def run_unpair(_options, args)
120
+ checked = name_and_id(args)
121
+ return checked if checked.is_a?(Integer)
122
+
123
+ name, id = checked
124
+ unless @access.peer_unpair(id, name)
125
+ error_line("#{command_name}: #{id[0, 8]} isn't paired with #{name}")
126
+ return CLI::Exit::FAILED
127
+ end
128
+
129
+ @stdout.puts("#{id[0, 8]} unpaired from #{PeerMailbox.label(name)} (its messages stay)")
130
+ 0
131
+ end
132
+
133
+ def run_say(options, args)
134
+ return usage_error("give --wake or --nowake") unless options.key?(:wake)
135
+
136
+ wait = wait_seconds(options[:wait]) or return CLI::Exit::USAGE
137
+
138
+ checked = name_and_id(args)
139
+ return checked if checked.is_a?(Integer)
140
+
141
+ name, id = checked
142
+ text = utf8(options[:text] || read_stdin)
143
+ return usage_error("no text: pass -m TEXT or pipe it in") if text.nil? || text.strip.empty?
144
+
145
+ said = @access.peer_say(id, name, text: text, summary: options[:summary], wake: options[:wake], re: options[:re],
146
+ wait: wait, **(@sleeper ? { sleeper: @sleeper } : {}))
147
+ unless said.received?
148
+ error_line("#{command_name}: #{said.line(name)}")
149
+ return CLI::Exit::FAILED
150
+ end
151
+
152
+ @stdout.puts(said.line(name))
153
+ said.receipt&.state == "refused" ? CLI::Exit::FAILED : 0
154
+ end
155
+
156
+ # --wait's seconds (0 without it); nil after its usage error.
157
+ def wait_seconds(value)
158
+ return 0 if value.nil?
159
+
160
+ seconds = Float(value, exception: false)
161
+ return seconds if seconds&.between?(0, PeerSay::WAIT_MAX)
162
+
163
+ usage_error("--wait takes seconds from 0 to #{PeerSay::WAIT_MAX}, not #{value.inspect}")
164
+ nil
165
+ end
166
+
167
+ def run_ls(options, args)
168
+ refused = format_refusal(options[:format])
169
+ return refused if refused
170
+ return usage_error("give the session ID") unless args.size == 1
171
+
172
+ id = @access.resolve_id(args.first)
173
+ peers = @access.peer_list(id)
174
+ if options[:format] == "json"
175
+ @stdout.puts(JSON.pretty_generate(peers.map(&:to_h)))
176
+ elsif peers.empty?
177
+ @stdout.puts("no peers")
178
+ else
179
+ peers.each { |peer| print_peer(peer) }
180
+ end
181
+ 0
182
+ end
183
+
184
+ def print_peer(peer)
185
+ paired = peer.paired? ? "paired #{peer.paired_at}#{" by #{peer.from}" if peer.from}" : "not paired"
186
+ @stdout.puts("#{peer.name} #{paired}#{" sends to #{peer.address}" if peer.address}")
187
+ peer.messages.each do |row|
188
+ @stdout.puts(" ##{row.serial} #{PeerRoster.state_words(row.receipt)} #{row.summary}".rstrip)
189
+ end
190
+ end
191
+ end
192
+ end