samagotchi 0.188.0 → 0.190.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 (112) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +76 -1
  3. data/docs/architecture.md +9 -4
  4. data/docs/bundle-authoring.md +1 -1
  5. data/docs/bundles.md +15 -0
  6. data/docs/cli.md +38 -9
  7. data/docs/configuration.md +1 -0
  8. data/docs/guardrails.md +22 -9
  9. data/docs/internals/attached-context.md +4 -1
  10. data/docs/internals/bundles.md +3 -3
  11. data/docs/internals/engine.md +18 -2
  12. data/docs/internals/pages.md +65 -18
  13. data/docs/internals/session-lifecycle.md +19 -6
  14. data/docs/internals/web-frontend.md +3 -3
  15. data/docs/internals/web-push.md +11 -5
  16. data/docs/pages.md +69 -15
  17. data/docs/peers.md +3 -0
  18. data/docs/plugins.md +25 -1
  19. data/docs/releasing.md +1 -1
  20. data/docs/scheduling.md +168 -11
  21. data/docs/sessions.md +4 -4
  22. data/docs/sub-agent.md +1 -1
  23. data/docs/testing.md +1 -1
  24. data/lib/samagotchi/bundle_manifest.rb +34 -5
  25. data/lib/samagotchi/bundles/guardrails/guardrails/rules.yml +15 -0
  26. data/lib/samagotchi/bundles/guardrails/manifest.yml +2 -2
  27. data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
  28. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +169 -0
  29. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  30. data/lib/samagotchi/bundles/system/self_map.md +2 -2
  31. data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
  32. data/lib/samagotchi/config.rb +2 -0
  33. data/lib/samagotchi/context_fetch.rb +9 -3
  34. data/lib/samagotchi/engine/models.rb +6 -4
  35. data/lib/samagotchi/engine/turn_end.rb +20 -2
  36. data/lib/samagotchi/engine.rb +5 -1
  37. data/lib/samagotchi/failure_line.rb +43 -0
  38. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  39. data/lib/samagotchi/guardrails/chi_dirs.rb +20 -5
  40. data/lib/samagotchi/guardrails/parent_approvals.rb +1 -1
  41. data/lib/samagotchi/guardrails/protected_paths.rb +8 -4
  42. data/lib/samagotchi/guardrails/shell_paths.rb +16 -2
  43. data/lib/samagotchi/guardrails/targets.rb +1 -1
  44. data/lib/samagotchi/guardrails/verdict.rb +5 -3
  45. data/lib/samagotchi/image_store.rb +4 -0
  46. data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
  47. data/lib/samagotchi/last_turn.rb +2 -1
  48. data/lib/samagotchi/llm/utf8_scrub.rb +26 -0
  49. data/lib/samagotchi/llm_context_view.rb +6 -0
  50. data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
  51. data/lib/samagotchi/memory_bundle/builder.rb +1 -0
  52. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  53. data/lib/samagotchi/model_profile.rb +4 -1
  54. data/lib/samagotchi/page_command.rb +9 -6
  55. data/lib/samagotchi/pages/bundled.rb +83 -0
  56. data/lib/samagotchi/pages/launch.rb +14 -2
  57. data/lib/samagotchi/pages/runner.rb +7 -2
  58. data/lib/samagotchi/pages/runtime.rb +84 -0
  59. data/lib/samagotchi/pages/store.rb +18 -5
  60. data/lib/samagotchi/pages.rb +47 -3
  61. data/lib/samagotchi/peer_continue.rb +14 -8
  62. data/lib/samagotchi/reply_wait.rb +1 -1
  63. data/lib/samagotchi/run_options.rb +1 -1
  64. data/lib/samagotchi/schedule_command.rb +175 -39
  65. data/lib/samagotchi/schedule_display.rb +85 -0
  66. data/lib/samagotchi/schedules/busy_part.rb +146 -0
  67. data/lib/samagotchi/schedules/condition_part.rb +312 -0
  68. data/lib/samagotchi/schedules/edit_part.rb +144 -0
  69. data/lib/samagotchi/schedules/history_part.rb +51 -0
  70. data/lib/samagotchi/schedules/listing_part.rb +52 -0
  71. data/lib/samagotchi/schedules/notices_part.rb +122 -0
  72. data/lib/samagotchi/schedules/protection_part.rb +113 -0
  73. data/lib/samagotchi/schedules/prune_part.rb +79 -0
  74. data/lib/samagotchi/schedules/recurrence.rb +103 -0
  75. data/lib/samagotchi/schedules.rb +188 -409
  76. data/lib/samagotchi/session_access/local.rb +9 -1
  77. data/lib/samagotchi/session_access/remote.rb +2 -1
  78. data/lib/samagotchi/session_chain/delete.rb +7 -5
  79. data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
  80. data/lib/samagotchi/session_lifecycle.rb +3 -2
  81. data/lib/samagotchi/session_manager/removal.rb +16 -9
  82. data/lib/samagotchi/session_protection.rb +99 -0
  83. data/lib/samagotchi/session_retention.rb +21 -6
  84. data/lib/samagotchi/sessions_command.rb +4 -0
  85. data/lib/samagotchi/system_one/self_protect.rb +4 -2
  86. data/lib/samagotchi/testing/boundary.rb +13 -0
  87. data/lib/samagotchi/tools/cancel_schedule.rb +32 -4
  88. data/lib/samagotchi/tools/execute.rb +5 -1
  89. data/lib/samagotchi/tools/list_schedules.rb +1 -0
  90. data/lib/samagotchi/tools/task_runtime.rb +6 -0
  91. data/lib/samagotchi/turn_endings.rb +14 -2
  92. data/lib/samagotchi/turn_flow.rb +2 -1
  93. data/lib/samagotchi/turn_outcome.rb +41 -0
  94. data/lib/samagotchi/version.rb +1 -1
  95. data/lib/samagotchi/web/page_routes.rb +13 -8
  96. data/lib/samagotchi/web/public/app.js +12 -18
  97. data/lib/samagotchi/web/public/index.html +11 -2
  98. data/lib/samagotchi/web/public/owner_claim.js +7 -5
  99. data/lib/samagotchi/web/public/page_links.js +1 -1
  100. data/lib/samagotchi/web/public/page_view.js +8 -5
  101. data/lib/samagotchi/web/public/pages.css +9 -2
  102. data/lib/samagotchi/web/public/pages_group.js +21 -19
  103. data/lib/samagotchi/web/public/pages_list.js +73 -0
  104. data/lib/samagotchi/web/public/pages_model.js +54 -0
  105. data/lib/samagotchi/web/public/pages_wiring.js +66 -0
  106. data/lib/samagotchi/web/public/stream_handlers.js +8 -0
  107. data/lib/samagotchi/web/public/views.js +77 -23
  108. data/lib/samagotchi/web/push/notifier.rb +4 -3
  109. data/lib/samagotchi/web/server.rb +3 -1
  110. data/lib/samagotchi/web/session_hub.rb +75 -19
  111. data/lib/samagotchi/worker.rb +6 -4
  112. metadata +20 -1
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The Schedules page (#/p/schedules), from the schedules bundle
4
+ # (docs/scheduling.md): every durable schedule, why one is off, and the
5
+ # recent runs. Read-only: chi changes a schedule when asked, or
6
+ # `chi schedule enable ID` and the rest do. To make it your own, copy this
7
+ # file to ~/.config/samagotchi/pages/schedules.rb (chi page list --format
8
+ # json gives its path as script) and change it: yours replaces this one.
9
+
10
+ require "time"
11
+
12
+ # The text reads as plain text too (chi web's Markdown is off by default): no
13
+ # headings or bold, only `code` around a command.
14
+
15
+ # How many rows each table shows; the rest are counted, not drawn.
16
+ SCHEDULE_ROWS = 100
17
+ RUN_ROWS = 50
18
+ # How many lines the "Turned off" and "Can't be read" texts show, and how
19
+ # much of a name or a reason a line keeps: a text block holds at most 16 KB,
20
+ # and schedule.max_total can be raised.
21
+ TEXT_LINES = 20
22
+ NAME_CHARS = 60
23
+ REASON_CHARS = 80
24
+
25
+ def cut(text, chars) = text.size > chars ? "#{text[0, chars - 1]}…" : text
26
+
27
+ # The first TEXT_LINES of +lines+, and a line counting the rest.
28
+ def capped(lines, rest_hint)
29
+ return lines if lines.size <= TEXT_LINES
30
+
31
+ lines.first(TEXT_LINES) + ["- and #{lines.size - TEXT_LINES} more: #{rest_hint}"]
32
+ end
33
+
34
+ # A time as the page shows it, in this machine's zone; nil for none.
35
+ def clock(iso)
36
+ return nil if iso.nil? || iso.to_s.empty?
37
+
38
+ Time.iso8601(iso.to_s).localtime.strftime("%Y-%m-%d %H:%M")
39
+ rescue ArgumentError
40
+ iso.to_s
41
+ end
42
+
43
+ def plural(count, word) = "#{count} #{word}#{"s" unless count == 1}"
44
+
45
+ # A failure that turned it off before its budget ran out: a one-off's.
46
+ def failed_once?(schedule) = schedule.failures < schedule.max_failures
47
+
48
+ # The State column: on, firing, or off with why (off_reason).
49
+ def state_words(schedule)
50
+ case schedule.off_reason
51
+ when nil then schedule.state
52
+ when "owner" then "off: you"
53
+ when "skips" then "off: #{plural(schedule.skips, "skip")}"
54
+ when "failures" then failed_once?(schedule) ? "off: failed" : "off: #{plural(schedule.failures, "failure")}"
55
+ when "done" then "done"
56
+ when "missed" then "missed"
57
+ else "off"
58
+ end
59
+ end
60
+
61
+ # Why an off schedule is off, in a sentence's words.
62
+ def why_off(schedule)
63
+ case schedule.off_reason
64
+ when "owner" then "turned off by you"
65
+ when "skips" then "skipped #{plural(schedule.skips, "time")} (#{schedule.skip_window})"
66
+ when "failures" then failed_once?(schedule) ? "one-off, failed" : "failed #{plural(schedule.failures, "time")}"
67
+ when "done" then "one-off, done"
68
+ when "missed" then "one-off, missed"
69
+ else "off"
70
+ end
71
+ end
72
+
73
+ # What the last skip or failure said (a budget's last row reads "disabled: …").
74
+ def last_reason(schedule)
75
+ row = schedule.history.reverse.find { |run| %w[skipped failed].include?(run.status) }
76
+ row&.detail.to_s.delete_prefix("disabled: ")
77
+ end
78
+
79
+ def off_line(schedule)
80
+ line = "- #{cut(schedule.name.to_s, NAME_CHARS)} — #{why_off(schedule)}"
81
+ reason = %w[skips failures].include?(schedule.off_reason) ? cut(last_reason(schedule), REASON_CHARS) : ""
82
+ line += ": #{reason}" unless reason.empty?
83
+ line + " · #{turn_on(schedule)}"
84
+ end
85
+
86
+ # How to turn it on again. Enable alone brings back only a schedule with a
87
+ # next time: a spent one-off (fired, failed, missed) has none, and enabled it
88
+ # would read "on" and never fire. It gets a new moment first (edit keeps it
89
+ # off), then enable.
90
+ def turn_on(schedule)
91
+ return "`chi schedule enable #{schedule.id}`" if schedule.next_due
92
+
93
+ "to run it again: `chi schedule edit #{schedule.id} --date YYYY-MM-DDTHH:MM`, then `chi schedule enable #{schedule.id}`"
94
+ end
95
+
96
+ # The If column: the owner's `--if CMD` (chi runs it before each firing;
97
+ # a "not needed" moves the schedule to its next time), cut; nil for none.
98
+ def if_words(schedule)
99
+ condition = schedule.condition
100
+ return nil if condition.nil?
101
+
102
+ cmd = condition.is_a?(Hash) ? condition["cmd"] : nil
103
+ cmd.is_a?(String) ? cut(cmd, NAME_CHARS) : "(can't be read)"
104
+ end
105
+
106
+ def unreadable_lines(ids)
107
+ lines = ids.compact.map do |id|
108
+ # An id too long to show can't be given to cancel either.
109
+ next "- schedule #{cut(id, NAME_CHARS)} can't be read: fix or remove it in schedules.json" if id.size > NAME_CHARS
110
+
111
+ "- schedule #{id} can't be read: `chi schedule cancel #{id}` removes it"
112
+ end
113
+ lines = capped(lines, "`chi schedule list` names none of them; schedules.json has them")
114
+ nameless = ids.count(nil)
115
+ lines << "- #{plural(nameless, "schedule")} with no id can't be read: fix or remove it in schedules.json" if nameless.positive?
116
+ lines
117
+ end
118
+
119
+ page "Schedules" do |ui|
120
+ list = runtime.schedules
121
+ if list.entries.empty? && list.unreadable_ids.empty?
122
+ ui.text "No schedules yet. Ask chi (\"check the CI every morning at 9\") or run " \
123
+ "`chi schedule add --session ID --every 1d -m \"…\"`; see docs/scheduling.md."
124
+ next
125
+ end
126
+
127
+ counts = list.entries.map(&:state).tally
128
+ states = %w[on firing off].filter_map { |state| "#{counts[state]} #{state}" if counts[state] }
129
+ summary = "#{plural(list.entries.size, "schedule")}#{": #{states.join(", ")}" unless states.empty?}. Refresh to update."
130
+ ui.text [summary, list.warning].compact.join("\n\n")
131
+
132
+ off = list.entries.select { |schedule| schedule.state == "off" }
133
+ ui.text "Turned off:\n\n#{capped(off.map { |schedule| off_line(schedule) }, "`chi schedule list --all`").join("\n")}" unless off.empty?
134
+ ui.text "Can't be read:\n\n#{unreadable_lines(list.unreadable_ids).join("\n")}" unless list.unreadable_ids.empty?
135
+
136
+ next if list.entries.empty?
137
+
138
+ # On (and firing) first by next due (a firing one-off has none: last of them), then off.
139
+ by_next = ->(schedule) { [schedule.next_due ? 0 : 1, schedule.next_due.to_s, schedule.id.to_s] }
140
+ ordered = list.entries.reject { |schedule| schedule.state == "off" }.sort_by(&by_next) + off
141
+ rows = ordered.first(SCHEDULE_ROWS).map do |schedule|
142
+ { "name" => schedule.name, "state" => state_words(schedule), "when" => schedule.recurrence_words,
143
+ "next" => clock(schedule.next_due), "last_run" => clock(schedule.last_fired), "last_result" => schedule.last_result,
144
+ "skips" => "#{schedule.skips}/#{schedule.max_skips}", "failures" => "#{schedule.failures}/#{schedule.max_failures}",
145
+ "if" => if_words(schedule), "mode" => schedule.mode, "id" => schedule.id.to_s[0, 8] }
146
+ end
147
+ more = ordered.size - rows.size
148
+ ui.text "Schedules#{"\n\nThe first #{SCHEDULE_ROWS}; #{more} more in `chi schedule list --all`." if more.positive?}"
149
+ ui.table rows, columns: { "name" => "Name", "state" => "State", "when" => "When", "next" => "Next", "last_run" => "Last run",
150
+ "last_result" => "Last result", "skips" => "Skips", "failures" => "Failures", "if" => "If",
151
+ "mode" => "Mode", "id" => "ID" },
152
+ key: %w[state next]
153
+
154
+ runs = list.entries.flat_map { |schedule| schedule.history.map { |run| [schedule, run] } }
155
+ .sort_by { |_schedule, run| run.at.to_s }.reverse
156
+ if runs.empty?
157
+ ui.text "Recent runs\n\nNo runs recorded yet."
158
+ next
159
+ end
160
+
161
+ shown = runs.first(RUN_ROWS)
162
+ ui.text "Recent runs#{"\n\nThe last #{RUN_ROWS} of #{runs.size}; `chi schedule show ID` has each one's." if runs.size > RUN_ROWS}"
163
+ ui.table shown.map { |schedule, run|
164
+ { "when" => clock(run.at), "schedule" => schedule.name, "what" => run.status, "why" => run.detail,
165
+ "session" => run.session_id&.slice(0, 8) }
166
+ },
167
+ columns: { "when" => "When", "schedule" => "Schedule", "what" => "What", "why" => "Why", "session" => "Session" },
168
+ key: %w[schedule what]
169
+ end
@@ -1,14 +1,14 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.188.0
3
+ version: 0.190.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
7
7
  identity.md: sha256:29c2f7df9f6c5acbc5ec17000a4490741e55e426af15ca0d81c8706edd9bd027
8
- self_map.md: sha256:c46fefc568b9b57c907ecc04f34b181dcc92d1cbcc40ef878a66b3973d79792f
8
+ self_map.md: sha256:5c5b4414f91daa74b436fde4afc77200d3629327f5b465fac40181ebcda7cc01
9
9
  config_modification_protocol.md: sha256:03fdf3ea3138449bc73f73eaa5604cc5d702777c20499ec13ca32b7696e6d37f
10
10
  memory_guide.md: sha256:272443ff8292631b28239cb8431d6e8dd19aa23fc53d05e1a10c11696a0a5d8d
11
11
  delegated.md: sha256:a0d6ddcd4a8be06526d964898611775fd251cfd9d145a9d16afaccaa503597bd
12
12
  skill_pages.md:
13
- sha256: sha256:be6071ce6195ffb3c8340cb458fd5d181f9ef86c87bda44b840f7bf066648478
13
+ sha256: sha256:e5a19c6eae13698f3fa475dd3068368f3cc81c36b1fc6bc4aa6fc9fa2bdc5683
14
14
  description: "Make, change or remove a page in chi web (a table, text or a walk the user reopens at #/p/NAME): write the script, chi page run, check, link"
@@ -71,8 +71,8 @@
71
71
  `docs/bundle-authoring.md` in my source dir first.
72
72
 
73
73
  - Pages: `chi page run|list|rm` runs, lists and removes pages, Ruby scripts in the `pages/` folder beside the
74
- config file whose stored result chi web shows at `#/p/NAME`; how I make one is the `skill_pages` memory
75
- (`docs/pages.md`).
74
+ config file (or a bundle's, as the schedules bundle's) whose stored result chi web shows at `#/p/NAME`; how I make
75
+ one is the `skill_pages` memory (`docs/pages.md`).
76
76
 
77
77
  An MCP host or a script can drive me: `docs/mcp-server.md`, `docs/thin-clients.md`.
78
78
 
@@ -20,8 +20,8 @@ question at hand: that stays in your answer.
20
20
  5. On `error: line N: …` fix that line with edit and run again. The last good result stays meanwhile, so a
21
21
  bad edit never blanks the page.
22
22
  6. Answer in one or two lines: what the page shows, the link [Title](#/p/NAME) as a plain Markdown link, and
23
- that Refresh on the page runs it again. Always add that it is in All sessions, under Pages: Markdown is off by
24
- default, and then the link is plain text. Never put the link in backticks: a code span can't be clicked.
23
+ that Refresh on the page runs it again. Always add that it is under the `pages` pill in chi web's top bar:
24
+ Markdown is off by default, and then the link is plain text. Never put the link in backticks: a code span can't be clicked.
25
25
  7. To change a page: edit the script, run it again (steps 3-4). To remove one: `chi page rm NAME`.
26
26
 
27
27
  ## Never
@@ -77,8 +77,13 @@ What trips a script:
77
77
  fine for a few dozen; group in Ruby). Its `turn_records` are only the newest turn's: for anything per turn
78
78
  or per day, read every turn from `<sessions dir>/ID/analytics.json` (`turn_records`: `completed_at`,
79
79
  `model_ref`, `cost` as reported, `cost_estimate` from the configured price; either may be missing). `chi self`
80
- names the sessions dir. Schedules: `chi schedule list --all --format json`. `json` is loaded; `require`
81
- anything else.
80
+ names the sessions dir. `json` is loaded; `require` anything else.
81
+ - Schedules: `runtime.schedules` in the script reads them in chi itself (no command): each has `id`, `name`,
82
+ `state` (on, firing, off), `off_reason`, `next_due`, `last_fired`, `last_result`, `skips`, `failures` and
83
+ `history` (runs: `at`, `status`, `detail`, `session_id`), the keys of `chi schedule list --all --format json`;
84
+ `ui.table runtime.schedules.rows, columns: …` takes them as rows, and `.warning` says when nothing ticks.
85
+ For a ready page: `chi bundle install schedules`. To make it your own, copy its script (`chi page list
86
+ --format json` names it as `script`) to `<the pages folder>/schedules.rb` and change that.
82
87
  - Check that a command worked (`status.success?`, `$?.success?`) and `raise` with a plain message when it
83
88
  didn't: the page then says why.
84
89
 
@@ -180,6 +180,8 @@ module Samagotchi
180
180
  # What one chain and one machine may hold, so a routine that re-schedules itself cannot multiply its entries.
181
181
  Entry.new(key: "schedule.max_per_session", yaml_path: %w[schedule max_per_session], type: :integer, default: 10, expose: %i[env config], lifecycle: :next_cli_run),
182
182
  Entry.new(key: "schedule.max_total", yaml_path: %w[schedule max_total], type: :integer, default: 50, expose: %i[env config], lifecycle: :next_cli_run),
183
+ # How long a schedule's condition (--if CMD) may run before it is killed and counted as a failure (1..300).
184
+ Entry.new(key: "schedule.condition_timeout_seconds", yaml_path: %w[schedule condition_timeout_seconds], type: :integer, default: 30, expose: %i[env config], lifecycle: :next_cli_run),
183
185
 
184
186
  # Images sent to a model (ImageStore): the long side they are downscaled
185
187
  # to, the most bytes one may take (bigger → re-encoded as jpeg), and how
@@ -35,8 +35,13 @@ module Samagotchi
35
35
  # replaced while it ran: nothing recorded for it).
36
36
  Outcome = Data.define(:status, :snapshot, :error)
37
37
  # What the command did: +output+ its stdout, +error+ nil or why it
38
- # failed, +cancelled+ the caller stopped it.
39
- Run = Data.define(:output, :error, :stderr, :cancelled)
38
+ # failed, +cancelled+ the caller stopped it, +status+ its
39
+ # Process::Status when it ended on its own within the cap (nil when it
40
+ # was stopped: a timeout, the cap, a cancel; or never ran), so a caller
41
+ # telling exit codes apart never reads a TERM trap's exit 0 as a pass.
42
+ Run = Data.define(:output, :error, :stderr, :cancelled, :status) do
43
+ def initialize(output:, error:, stderr:, cancelled:, status: nil) = super
44
+ end
40
45
 
41
46
  module_function
42
47
 
@@ -137,9 +142,10 @@ module Samagotchi
137
142
 
138
143
  # Checked again once the reader is done: a command that exits before
139
144
  # wait's next tick never gets an over from it.
145
+ ended = error.nil? && !out_reader.over?
140
146
  error = OVER_CAP if out_reader.over?
141
147
  error ||= exit_error(status, stderr_text)
142
- Run.new(output: out_reader.text, error: error, stderr: stderr_text, cancelled: false)
148
+ Run.new(output: out_reader.text, error: error, stderr: stderr_text, cancelled: false, status: ended ? status : nil)
143
149
  rescue SystemCallError => e
144
150
  Run.new(output: nil, error: "couldn't run it: #{e.message}", stderr: "", cancelled: false)
145
151
  ensure
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "../config"
4
4
  require_relative "../effective_model"
5
+ require_relative "../failure_line"
5
6
  require_relative "../llm/backend"
6
7
  require_relative "../llm/errors"
7
8
  require_relative "../log"
@@ -91,12 +92,13 @@ module Samagotchi
91
92
  end
92
93
  private :record_prompt_parts
93
94
 
94
- # A failed turn's one line (the error's #summary). A host's failure
95
- # under an alias says what the alias became (HostRegistry#alias_note):
96
- # "host main" alone doesn't tell --model splash's user it was splash.
95
+ # A failed turn's one line (FailureLine.for: the error's
96
+ # #summary, else "chi error: …"). A host's failure under an alias says
97
+ # what the alias became (HostRegistry#alias_note): "host main" alone
98
+ # doesn't tell --model splash's user it was splash.
97
99
  # @return [String]
98
100
  def failure_summary(error)
99
- summary = error.respond_to?(:summary) ? error.summary : error.message
101
+ summary = FailureLine.for(error)
100
102
  return summary unless error.is_a?(LLM::ProviderError) && error.host
101
103
 
102
104
  note = @host_registry.alias_note(effective_model_name)
@@ -16,8 +16,8 @@ module Samagotchi
16
16
  # @steer_cut, @hooks, @event_log, @client.
17
17
  module TurnEndPart
18
18
  # How the turn ended, on the session (Session#last_turn): the caller's
19
- # save puts it in the file the session hub watches. Public for the
20
- # Worker's turn that failed before it began (no #end_turn ran).
19
+ # save puts it in the file the session hub watches (#end_turn, and
20
+ # #fail_turn_not_begun where no #end_turn ran).
21
21
  # @param limit [Integer, nil] the turn ran out of iterations at this
22
22
  # limit: "exhausted" => true, "limit" => N, so a wait with nobody to
23
23
  # answer the continue offer says so (ReplyWait, ParentReport "limit")
@@ -32,6 +32,24 @@ module Samagotchi
32
32
  **stop_facts(event))
33
33
  end
34
34
 
35
+ # A turn that failed before the Engine's began (the Worker's steps
36
+ # before #run_turn raised, or #begin_turn did): idle again, its
37
+ # last_turn and its :turn_failed as an Engine turn's failure has
38
+ # them (TurnEndings#failed_event, the same line), with no
39
+ # :turn_started before it and nothing kept. Observers only (no turn
40
+ # sink); the caller logs it.
41
+ # @param origin [TurnOrigin] the turn's
42
+ # @param turn_id [String, nil] the id the turn would have run under
43
+ def fail_turn_not_begun(session, error, origin:, turn_id: nil)
44
+ synchronize_events do
45
+ event = failed_event(error, 0)
46
+ event[:turn_id] = turn_id if turn_id
47
+ session.status = Session::STATUS_IDLE
48
+ record_last_turn(session, "failed", 0, origin, event)
49
+ emit_event(nil, origin.empty? ? event : event.merge(origin: origin.to_h))
50
+ end
51
+ end
52
+
35
53
  # Why a turn stopped (TurnEndings#stop_facts).
36
54
  def stop_facts(event) = @turn_endings.stop_facts(event)
37
55
  private :stop_facts
@@ -954,7 +954,8 @@ module Samagotchi
954
954
  # only re-raised: the turn already ended; so is any error there. Any
955
955
  # other error (e.g. an LLM::ProviderError) emits :turn_failed and
956
956
  # re-raises; a provider error adds error_kind:, retryable:, host: and a
957
- # one-line summary:.
957
+ # one-line summary:, chi's own (FailureLine.chi_error?) error_kind:
958
+ # :chi_error and its summary: (logged with its backtrace, chi_error).
958
959
  def run_turn(session, prompt, on_event: nil, max_iterations: nil, cancel_controller: nil, max_tool_output_chars: nil, pending_input: nil, continue: false,
959
960
  origin: TurnOrigin::NONE, images: [], id: nil, resumed: false, resume_from: nil, verify: nil, revises: nil,
960
961
  input_waiting: nil, opener_source: nil, reply_for: nil)
@@ -997,6 +998,9 @@ module Samagotchi
997
998
  raise
998
999
  end
999
1000
 
1001
+ # chi's own failure: where it raised goes to the log (its line
1002
+ # says "details in samagotchi.log").
1003
+ Log.exception(:turn, "chi_error", e) if TurnEndings.chi_error?(e)
1000
1004
  # Keep what the turn got to (the prompt plus the loop's completed
1001
1005
  # tool iterations) like a cancel does, and save it: a worker exits
1002
1006
  # after a failed turn.
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "llm/errors"
4
+ require_relative "llm/utf8_scrub"
5
+
6
+ module Samagotchi
7
+ # Marks an error whose message tells the user what to change (an image
8
+ # the turn can't use, no model configured): a turn it fails shows that
9
+ # message as it is, never as a chi error (FailureLine.chi_error?).
10
+ module UserError
11
+ end
12
+
13
+ # The one line a failed turn shows (every UI, through the end event's
14
+ # summary: TurnEndings#failed_event) and its note keeps (TurnNote.failed:
15
+ # the reload's line, the model's; TurnFlow#prompt_turn_failed too), and
16
+ # whether chi itself failed. Light on purpose: the TUI's and chi web's
17
+ # thin loads reach it through TurnFlow.
18
+ module FailureLine
19
+ # A failed turn's error_kind when chi itself failed (.chi_error?).
20
+ CHI_ERROR = :chi_error
21
+ # The longest error message a chi error's line quotes.
22
+ MESSAGE_MAX = 300
23
+
24
+ module_function
25
+
26
+ # Whether +error+ is chi's own failure: neither the provider's
27
+ # (LLM::ProviderError, its own kind and summary) nor one that tells the
28
+ # user what to change (UserError).
29
+ def chi_error?(error) = !error.is_a?(LLM::ProviderError) && !error.is_a?(UserError)
30
+
31
+ # A provider error's summary, a UserError's message, else "chi error:
32
+ # <message> (<Class>); details in samagotchi.log". Its first line, read
33
+ # as UTF-8: the message may hold the bytes that failed.
34
+ # @return [String]
35
+ def for(error)
36
+ return error.summary if error.respond_to?(:summary)
37
+ return error.message unless chi_error?(error)
38
+
39
+ message = LLM::Utf8Scrub.call(error.message.to_s).lines.first.to_s.strip[0, MESSAGE_MAX]
40
+ "chi error: #{message} (#{error.class.name}); details in samagotchi.log"
41
+ end
42
+ end
43
+ end
@@ -273,6 +273,7 @@ module Samagotchi
273
273
  require_relative "chi_home"
274
274
  require_relative "chi_shim"
275
275
  require_relative "paths"
276
+ require_relative "guardrails/chi_dirs"
276
277
  Guardrails::ProtectedPaths.new(
277
278
  store_dir: File.dirname(@approvals.path),
278
279
  bundles_dir: InstalledBundles.dir,
@@ -283,7 +284,8 @@ module Samagotchi
283
284
  runs_dir: File.join(File.dirname(@approvals.path, 2), "system_one"),
284
285
  home_path: ChiHome.path,
285
286
  shim_path: ChiShim.path,
286
- plugins_dir: File.join(Paths.state_dir, "plugins")
287
+ plugins_dir: File.join(Paths.state_dir, "plugins"),
288
+ schedules_path: Guardrails::ChiDirs.schedules_file
287
289
  )
288
290
  end
289
291
  end
@@ -13,10 +13,12 @@ module Samagotchi
13
13
  # (read each call). Each surface keeps its set:
14
14
  # .protected the config dir, the hooks dir, the approval store's
15
15
  # dir, the installed bundles' dir, attached context,
16
- # the peer mailbox, System 1's saved runs: an ask only the user may answer
16
+ # the peer mailbox, System 1's saved runs, and one file,
17
+ # schedules.json: an ask only the user may answer
17
18
  # (ParentApprovals.chi_files?)
18
19
  # .touches .protected and the session repo's git hooks dir: a
19
- # rule's touches: chi_dirs (Targets#touches_chi?)
20
+ # rule's touches: chi_dirs (Targets#touches_chi?), with
21
+ # .touches_exact (the state dir itself, as a word)
20
22
  # .self_protect .protected and the whole state dir, resolved: what
21
23
  # System 1 never answers for (SelfProtect)
22
24
  # .review the state dir, the config dir and a hooks dir
@@ -29,16 +31,23 @@ module Samagotchi
29
31
 
30
32
  # chi's config dir, the hooks dir, the approval store's dir, the
31
33
  # installed bundles' dir, attached context, the peer mailbox (a message
32
- # there speaks as a peer) and System 1's saved runs
33
- # (labels there may train a model: no agent writes them).
34
+ # there speaks as a peer), System 1's saved runs
35
+ # (labels there may train a model: no agent writes them), and
36
+ # schedules.json, a file (#schedules_file: a schedule's prompt and its
37
+ # condition run unattended). The readers match a file root as a dir
38
+ # one: the path itself or under it (PathResolve.under?).
34
39
  def protected
35
40
  hooks = begin Hooks::Loader.hooks_dir rescue nil end
36
41
  bundles = begin MemoryPaths.bundles_dir rescue nil end
37
42
  [ConfigFile.config_dir, hooks, File.join(Paths.state_dir, "guardrails"), bundles, File.join(Paths.state_dir, "context"),
38
- File.join(Paths.state_dir, "mailbox"), File.join(Paths.state_dir, "system_one")]
43
+ File.join(Paths.state_dir, "mailbox"), File.join(Paths.state_dir, "system_one"), schedules_file]
39
44
  .compact.map { |dir| dir.to_s.chomp("/") }.reject(&:empty?).uniq
40
45
  end
41
46
 
47
+ # The schedules file, where Schedules#path has it for the default
48
+ # sessions dir: the state root above <state dir>/sessions.
49
+ def schedules_file = File.join(Paths.state_dir, "schedules.json")
50
+
42
51
  # .protected (as ParentApprovals.chi_dirs, the name its callers and
43
52
  # specs know) and the git hooks dir of +base+'s repo (+context+).
44
53
  def touches(context, base)
@@ -46,6 +55,12 @@ module Samagotchi
46
55
  ParentApprovals.chi_dirs + [context.hooks_dir(base)].compact
47
56
  end
48
57
 
58
+ # The dirs a shell word touches chi by naming exactly (not what is
59
+ # under them): the state dir, where a copy that names only the dir
60
+ # (`cp /tmp/schedules.json <state>/`, `mv`, `rsync`) lands a file root
61
+ # of .protected. Targets#touches_chi? reads it beside #touches.
62
+ def touches_exact = [Paths.state_dir]
63
+
49
64
  # .protected (as ParentApprovals.chi_dirs) and the whole state dir,
50
65
  # resolved.
51
66
  def self_protect
@@ -37,7 +37,7 @@ module Samagotchi
37
37
  # what only looks like one). samagotchi/context and samagotchi/mailbox
38
38
  # stop before a word character or a dot, so chi's own
39
39
  # lib/samagotchi/context_*.rb isn't one.
40
- CHI_TEXT = %r{\.config/samagotchi|samagotchi/config\.yml|samagotchi/hooks|samagotchi/guardrails|samagotchi/context(?![\w.])|samagotchi/mailbox(?![\w.])|memories/\.bundles}
40
+ CHI_TEXT = %r{\.config/samagotchi|samagotchi/config\.yml|samagotchi/hooks|samagotchi/guardrails|samagotchi/context(?![\w.])|samagotchi/mailbox(?![\w.])|samagotchi/schedules\.json(?![\w.])|memories/\.bundles}
41
41
  # The guardrails bundle's ask before a memory removal: its paths are in
42
42
  # the config dir, yet a parent may answer it.
43
43
  MEMORY_REMOVE_RULE = "memory-remove"
@@ -15,8 +15,10 @@ module Samagotchi
15
15
  # hooks, rules, manifests), attached context (a source's
16
16
  # command runs later, outside the gate; chi context writes
17
17
  # it), the peer mailbox (a message there speaks as a peer
18
- # agent; chi peer writes it) and System 1's saved runs (a
19
- # label there may train a model); nothing legitimate writes there through a tool
18
+ # agent; chi peer writes it), System 1's saved runs (a
19
+ # label there may train a model) and schedules.json (a
20
+ # schedule's prompt and condition run unattended; chi schedule
21
+ # writes it); nothing legitimate writes there through a tool
20
22
  # that says it writes.
21
23
  # ask (once / session): config.yml, home.json (the chi home: the
22
24
  # Ruby every chi launch boots), the chi shim (ChiShim: the
@@ -53,8 +55,9 @@ module Samagotchi
53
55
  # @param home_path [String, nil] home.json (ChiHome.path)
54
56
  # @param shim_path [String, nil] the chi shim (ChiShim.path)
55
57
  # @param plugins_dir [String, nil] <state dir>/plugins (the bundles' data, their secrets/ in it)
58
+ # @param schedules_path [String, nil] <state dir>/schedules.json (ChiDirs.schedules_file)
56
59
  def initialize(store_dir:, bundles_dir:, config_path:, hooks_dir:, context_dir: nil, runs_dir: nil, home_path: nil, shim_path: nil,
57
- plugins_dir: nil, mailbox_dir: nil)
60
+ plugins_dir: nil, mailbox_dir: nil, schedules_path: nil)
58
61
  @plugins_dir = plugins_dir
59
62
  # The same, spelled out: this state dir's own plugins/<x>/secrets.
60
63
  @secrets_text = plugins_dir && Regexp.union(SECRETS_TEXT, *([plugins_dir.to_s.chomp("/")] | PathResolve.reals(plugins_dir.to_s.chomp("/"))).map do |dir|
@@ -65,7 +68,8 @@ module Samagotchi
65
68
  ["installed-bundles", bundles_dir, "installed bundles (hooks, rules, manifests) are changed by chi bundle install"],
66
69
  ["chi-context", context_dir, "attached context sources run commands; change them with chi context"],
67
70
  ["chi-mailbox", mailbox_dir, "a message there speaks as a peer agent; chi peer writes the peer mailbox"],
68
- ["system-one-runs", runs_dir, "System 1's saved runs are chi's own record"]
71
+ ["system-one-runs", runs_dir, "System 1's saved runs are chi's own record"],
72
+ ["chi-schedules", schedules_path, "schedules run commands and prompts unattended; change them with chi schedule"]
69
73
  ]
70
74
  @ask = [
71
75
  ["chi-config", config_path, "changes chi's config.yml"],
@@ -39,9 +39,23 @@ module Samagotchi
39
39
  # @param text [Regexp] the fallback for a word that can't be resolved
40
40
  # @param cwd [String, nil] where the command starts
41
41
  # @param tmp_roots [Array<String>] where a .git/hooks part doesn't count
42
- def touches?(command, dirs:, text:, cwd:, home: Dir.home, env: ENV, tmp_roots: [])
42
+ # @param exact [Array<String>] dirs that count only as themselves, not
43
+ # what is under them (chi's state dir: `cp x <state>/` writes a file
44
+ # root there, schedules.json, by naming only the dir)
45
+ def touches?(command, dirs:, text:, cwd:, home: Dir.home, env: ENV, tmp_roots: [], exact: [])
43
46
  roots = dirs.compact.map { |dir| PathResolve.real(dir.to_s.chomp("/")) }.reject(&:empty?).uniq
44
- any_path?(command, text: text, cwd: cwd, home: home, env: env) { |path| names?(path, roots, tmp_roots) }
47
+ exact = exact.compact.map { |dir| PathResolve.real(dir.to_s.chomp("/")) }.reject(&:empty?).uniq
48
+ any_path?(command, text: text, cwd: cwd, home: home, env: env) do |path|
49
+ names?(path, roots, tmp_roots) || exactly?(path, exact)
50
+ end
51
+ end
52
+
53
+ def exactly?(path, exact)
54
+ return false if exact.empty?
55
+
56
+ PathResolve.reals(path.to_s.chomp("/")).any? do |real|
57
+ exact.any? { |dir| PathResolve.under?(real, dir) && PathResolve.under?(dir, real) }
58
+ end
45
59
  end
46
60
 
47
61
  # Whether a word of +command+ names a path the block holds for (each
@@ -510,7 +510,7 @@ module Samagotchi
510
510
  require_relative "parent_approvals"
511
511
  dirs = @chi_dirs ? @chi_dirs.call : ParentApprovals.chi_dirs
512
512
  shell_envs.any? do |home, env|
513
- ShellPaths.touches?(@command, dirs: dirs, text: ParentApprovals::CHI_SHELL_TEXT, cwd: @cwd, home: home,
513
+ ShellPaths.touches?(@command, dirs: dirs, exact: ChiDirs.touches_exact, text: ParentApprovals::CHI_SHELL_TEXT, cwd: @cwd, home: home,
514
514
  env: env, tmp_roots: Outside.tmp_roots)
515
515
  end
516
516
  end
@@ -20,13 +20,15 @@ module Samagotchi
20
20
  # parent model would be writing a model's prompt); and the bundle's
21
21
  # asks before answering chi's questions around chi answer (a parent
22
22
  # allowing one would answer a grandchild's question as the user); and
23
- # a shell command that names a bundle's secrets (ProtectedPaths).
23
+ # a shell command that names a bundle's secrets (ProtectedPaths); and
24
+ # a schedule's condition set from the shell (chi-schedule-if: a shell
25
+ # command chi's tick runs later, ungated).
24
26
  # A parent agent may never allow them (ParentApprovals.protected?,
25
27
  # ParentPolicy's user_only); System 1 may, only if the user lists the
26
28
  # rule by name in guardrails.system_one.rules, and never for the
27
- # chi-answer/chi-broadcast ones (SystemOne::SelfProtect::NEVER_AUTO).
29
+ # chi-answer/chi-broadcast/chi-schedule-if ones (SystemOne::SelfProtect::NEVER_AUTO).
28
30
  PROTECTED_RULES = %w[chi-config chi-home chi-shim chi-hooks shell-touches-chi chi-context-cmd chi-broadcast prompt-memory-write
29
- model-overlay-write chi-answer-piped chi-answer-http bundle-secrets-shell].freeze
31
+ model-overlay-write chi-answer-piped chi-answer-http bundle-secrets-shell chi-schedule-if].freeze
30
32
  SCOPES = %w[once session repo rule].freeze
31
33
  # Who answered an ask when it was a parent agent, not the user.
32
34
  PARENT_AGENT = "parent agent"
@@ -7,6 +7,7 @@ require "securerandom"
7
7
  require "tmpdir"
8
8
  require_relative "atomic_file"
9
9
  require_relative "config"
10
+ require_relative "failure_line"
10
11
 
11
12
  module Samagotchi
12
13
  # Reads an image's format and size from its first bytes, in pure Ruby.
@@ -235,7 +236,10 @@ module Samagotchi
235
236
  # Messages hold small refs to those files; the base64 is built only when
236
237
  # a request is sent.
237
238
  module ImageStore
239
+ # What the user sent can't be used (UserError: its message as it is).
238
240
  class Error < StandardError
241
+ include UserError
242
+
239
243
  # A ref to a file this session doesn't hold as an image: one wording
240
244
  # for a turn's refs (#check_refs) and a web upload's (#ref_for).
241
245
  def self.unknown_image(file) = new("unknown image #{file.to_s[0, 80]}")
@@ -43,6 +43,9 @@ module Samagotchi
43
43
  # script_names the scripts/ files it lists
44
44
  # context_providers Array<ContextProviders::Provider>
45
45
  # block_renderers Array<BlockRenderers::Renderer>
46
+ # pages the page scripts (pages:, Pages::Bundled): the
47
+ # kept manifest's only, [] from the record (a
48
+ # key a later manifest gains is never mirrored)
46
49
  # session_settings, session_setting_types, settings, setting_types
47
50
  # as Manifest reads them (settings nil when
48
51
  # the manifest said nothing of them)
@@ -62,7 +65,7 @@ module Samagotchi
62
65
  # the first chi that read it), {} from the record
63
66
  # origin :kept or :record
64
67
  class Manifest < Data.define(:name, :version, :requires_chi, :trust_level, :description, :needs,
65
- :script_names, :context_providers, :block_renderers, :session_settings,
68
+ :script_names, :context_providers, :block_renderers, :pages, :session_settings,
66
69
  :session_setting_types, :settings, :setting_types, :file_descriptions,
67
70
  :plugin_required, :plugin_parts, :includes, :unknown_keys, :floor_keys, :problems,
68
71
  :origin)
@@ -135,6 +138,7 @@ module Samagotchi
135
138
  script_names: pick.call("scripts", kept.scripts.keys, mirrored.script_names),
136
139
  context_providers: pick.call("context_providers", kept.context_providers, mirrored.context_providers),
137
140
  block_renderers: pick.call("block_renderers", kept.block_renderers, mirrored.block_renderers),
141
+ pages: pick.call("pages", kept.pages, mirrored.pages),
138
142
  session_settings: session.session_settings, session_setting_types: session.session_setting_types,
139
143
  settings: settings.settings, setting_types: settings.setting_types,
140
144
  file_descriptions: pick.call("files", kept.file_descriptions, mirrored.file_descriptions),
@@ -160,6 +164,7 @@ module Samagotchi
160
164
  script_names: bundle.scripts.keys,
161
165
  context_providers: parsed(problems, "context_providers", []) { ContextProviders.parse_list(raw["context_providers"]) },
162
166
  block_renderers: parsed(problems, "block_renderers", []) { BlockRenderers.parse_list(raw["block_renderers"]) },
167
+ pages: [],
163
168
  session_settings: list(raw["session_settings"]) || [],
164
169
  session_setting_types: types(raw["session_setting_types"]),
165
170
  settings: list(raw["settings"]),
@@ -218,6 +223,8 @@ module Samagotchi
218
223
  def context_providers? = !context_providers.empty?
219
224
 
220
225
  def block_renderers? = !block_renderers.empty?
226
+
227
+ def pages? = !pages.empty?
221
228
  end
222
229
  end
223
230
  end