samagotchi 0.189.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 (56) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +35 -1
  3. data/docs/architecture.md +4 -1
  4. data/docs/cli.md +17 -6
  5. data/docs/configuration.md +1 -0
  6. data/docs/guardrails.md +20 -8
  7. data/docs/internals/attached-context.md +4 -1
  8. data/docs/internals/engine.md +18 -2
  9. data/docs/pages.md +3 -2
  10. data/docs/scheduling.md +99 -5
  11. data/docs/sub-agent.md +1 -1
  12. data/lib/samagotchi/bundles/guardrails/guardrails/rules.yml +15 -0
  13. data/lib/samagotchi/bundles/guardrails/manifest.yml +2 -2
  14. data/lib/samagotchi/bundles/schedules/manifest.yml +4 -4
  15. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +13 -3
  16. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  17. data/lib/samagotchi/config.rb +2 -0
  18. data/lib/samagotchi/context_fetch.rb +9 -3
  19. data/lib/samagotchi/engine/models.rb +6 -4
  20. data/lib/samagotchi/engine/turn_end.rb +20 -2
  21. data/lib/samagotchi/engine.rb +5 -1
  22. data/lib/samagotchi/failure_line.rb +43 -0
  23. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  24. data/lib/samagotchi/guardrails/chi_dirs.rb +20 -5
  25. data/lib/samagotchi/guardrails/parent_approvals.rb +1 -1
  26. data/lib/samagotchi/guardrails/protected_paths.rb +8 -4
  27. data/lib/samagotchi/guardrails/shell_paths.rb +16 -2
  28. data/lib/samagotchi/guardrails/targets.rb +1 -1
  29. data/lib/samagotchi/guardrails/verdict.rb +5 -3
  30. data/lib/samagotchi/image_store.rb +4 -0
  31. data/lib/samagotchi/last_turn.rb +2 -1
  32. data/lib/samagotchi/llm/utf8_scrub.rb +26 -0
  33. data/lib/samagotchi/llm_context_view.rb +6 -0
  34. data/lib/samagotchi/model_profile.rb +4 -1
  35. data/lib/samagotchi/pages/runtime.rb +4 -3
  36. data/lib/samagotchi/reply_wait.rb +1 -1
  37. data/lib/samagotchi/schedule_command.rb +99 -5
  38. data/lib/samagotchi/schedule_display.rb +21 -5
  39. data/lib/samagotchi/schedules/condition_part.rb +312 -0
  40. data/lib/samagotchi/schedules/edit_part.rb +27 -3
  41. data/lib/samagotchi/schedules/notices_part.rb +8 -2
  42. data/lib/samagotchi/schedules/protection_part.rb +10 -0
  43. data/lib/samagotchi/schedules/prune_part.rb +79 -0
  44. data/lib/samagotchi/schedules.rb +57 -82
  45. data/lib/samagotchi/system_one/self_protect.rb +4 -2
  46. data/lib/samagotchi/tools/cancel_schedule.rb +27 -2
  47. data/lib/samagotchi/tools/execute.rb +5 -1
  48. data/lib/samagotchi/tools/list_schedules.rb +1 -0
  49. data/lib/samagotchi/tools/task_runtime.rb +6 -0
  50. data/lib/samagotchi/turn_endings.rb +14 -2
  51. data/lib/samagotchi/turn_flow.rb +2 -1
  52. data/lib/samagotchi/version.rb +1 -1
  53. data/lib/samagotchi/web/public/stream_handlers.js +8 -0
  54. data/lib/samagotchi/web/session_hub.rb +16 -5
  55. data/lib/samagotchi/worker.rb +6 -4
  56. metadata +4 -1
@@ -25,11 +25,13 @@ require_relative "state_format"
25
25
  require_relative "turn_outcome"
26
26
  require_relative "worker_link"
27
27
  require_relative "schedules/busy_part"
28
+ require_relative "schedules/condition_part"
28
29
  require_relative "schedules/edit_part"
29
30
  require_relative "schedules/history_part"
30
31
  require_relative "schedules/listing_part"
31
32
  require_relative "schedules/notices_part"
32
33
  require_relative "schedules/protection_part"
34
+ require_relative "schedules/prune_part"
33
35
  require_relative "schedules/recurrence"
34
36
 
35
37
  module Samagotchi
@@ -58,11 +60,13 @@ module Samagotchi
58
60
  # 30 s for a recap and 5 s for an archive, and an `add` must not wait on it.
59
61
  class Schedules
60
62
  include BusyPart
63
+ include ConditionPart
61
64
  include EditPart
62
65
  include HistoryPart
63
66
  include ListingPart
64
67
  include NoticesPart
65
68
  include ProtectionPart
69
+ include PrunePart
66
70
 
67
71
  FILE = "schedules.json"
68
72
  LOCK = "schedules.lock"
@@ -104,14 +108,16 @@ module Samagotchi
104
108
  # the session a same-mode turn was queued into. That is what makes
105
109
  # keep_links pruning provably safe: everything deleted is behind it.
106
110
  # `due_was` is the occurrence the last tick attempted: a skip or a failure
107
- # puts the clock back to it.
111
+ # puts the clock back to it. `condition` is the owner's `--if CMD`
112
+ # (ConditionPart), nil for none.
108
113
  Entry = Data.define(:id, :title, :anchor, :head, :mode, :prompt, :recurrence, :busy, :catch_up,
109
114
  :keep_links, :max_failures, :max_skips, :next_due, :due_was, :last_fired, :last_result,
110
115
  :firing_since, :firing_token, :pending_session_id, :pending_turn_id, :failures, :skips, :enabled,
111
- :created_at, :disabled_notice, :history, :extra) do
116
+ :created_at, :disabled_notice, :history, :condition, :extra) do
112
117
  # The recurrence comes back from JSON with string keys: every reader of
113
118
  # it below matches on `recurrence[:kind]`, so it is symbolised here once
114
- # (the disabled notice too, whose fields the claim hands on as is).
119
+ # (the disabled notice too, whose fields the claim hands on as is; the
120
+ # condition and its hidden next_due: ConditionPart.stored).
115
121
  def self.from_record(record)
116
122
  fields = record.attributes
117
123
  recurrence = fields[:recurrence]
@@ -119,7 +125,7 @@ module Samagotchi
119
125
  notice = fields[:disabled_notice]
120
126
  fields[:disabled_notice] = notice.is_a?(Hash) ? notice.transform_keys(&:to_sym) : nil
121
127
  fields[:history] = HistoryPart.rows(fields[:history])
122
- new(**fields, extra: record.extra)
128
+ new(**ConditionPart.stored(fields, record.extra))
123
129
  end
124
130
 
125
131
  def to_h
@@ -182,13 +188,16 @@ module Samagotchi
182
188
  StateFormat.added(:disabled_notice, in_version: VERSION, default: nil),
183
189
  # The last outcomes, newest last (HistoryPart).
184
190
  StateFormat.added(:history, in_version: VERSION, default: []),
191
+ # {cmd:, by: "cli", set_at:}: the owner's `--if CMD` (ConditionPart).
192
+ StateFormat.added(:condition, in_version: VERSION, default: nil),
185
193
  StateFormat.extra(:extra, in_version: VERSION)
186
194
  ],
187
195
  document_members: [StateFormat.added(:last_tick_at, in_version: VERSION, default: nil)]
188
196
  )
189
197
 
190
- # What one entry did in a tick: "fired", "skipped", "missed", "failed" or
191
- # "dry" (a --dry-run's "would fire"). +detail+ is the reason. +disabled+:
198
+ # What one entry did in a tick: "fired", "skipped", "missed", "failed",
199
+ # "not-needed" (its condition said no: ConditionPart) or "dry" (a
200
+ # --dry-run's "would fire"). +detail+ is the reason. +disabled+:
192
201
  # this skip or failure used up a recurring entry's budget (#mark_disabled).
193
202
  Outcome = Data.define(:id, :title, :status, :detail, :entry, :disabled, :session_id) do
194
203
  def initialize(id:, status:, title: nil, detail: nil, entry: nil, disabled: false, session_id: nil) = super
@@ -205,12 +214,17 @@ module Samagotchi
205
214
  # its lock sit in the state root above it (docs/scheduling.md), so the
206
215
  # session listing never mistakes it for a session
207
216
  # @param clock [#call] "now", as a Time
208
- def initialize(state_dir: nil, clock: -> { Time.now })
217
+ # @param condition_runner [#call] runs a condition's CMD (ConditionPart::DEFAULT_RUNNER)
218
+ # @param monotonic [#call] seconds, for the time the condition pre-pass took
219
+ def initialize(state_dir: nil, clock: -> { Time.now }, condition_runner: ConditionPart::DEFAULT_RUNNER,
220
+ monotonic: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
209
221
  @state_dir = state_dir || Session.default_state_dir
210
222
  # ~/.local/state/samagotchi for the default sessions dir; expand_path
211
223
  # first so a trailing slash does not make the parent the sessions dir.
212
224
  @store_dir = File.dirname(File.expand_path(@state_dir))
213
225
  @clock = clock
226
+ @condition_runner = condition_runner
227
+ @monotonic = monotonic
214
228
  end
215
229
 
216
230
  attr_reader :state_dir, :store_dir
@@ -255,11 +269,15 @@ module Samagotchi
255
269
  # @return [Entry]
256
270
  # @raise [Usage] the add is wrong
257
271
  # @raise [Session::NotFound, Session::AmbiguousId] no such session
272
+ # +condition+ is the owner's `--if CMD` (ConditionPart): the CLI's only,
273
+ # never a tool's.
258
274
  def add(target:, prompt:, recurrence:, title: nil, mode: CHAIN, catch_up: nil, keep_links: nil,
259
- max_failures: nil, max_skips: nil)
275
+ max_failures: nil, max_skips: nil, condition: nil)
260
276
  raise Usage, "a schedule needs a session to run against" if target.to_s.strip.empty?
261
277
  raise Usage, "mode must be one of #{MODES.join(", ")}" unless MODES.include?(mode)
262
278
 
279
+ condition = condition.nil? ? nil : condition_for(condition, recurrence)
280
+
263
281
  given_catch_up = catch_up.nil? || catch_up.to_s.strip.empty? ? Config.get("schedule.default_catch_up") : catch_up.to_s.strip
264
282
  validate_catch_up!(given_catch_up)
265
283
  prompt = validate_prompt!(prompt)
@@ -294,7 +312,7 @@ module Samagotchi
294
312
  next_due: next_due_for(recurrence, from: now).utc.iso8601, due_was: nil,
295
313
  last_fired: nil, last_result: nil, firing_since: nil, firing_token: nil, pending_session_id: nil,
296
314
  pending_turn_id: nil, failures: 0, skips: 0, enabled: true, created_at: now.utc.iso8601,
297
- disabled_notice: nil, history: [], extra: {}
315
+ disabled_notice: nil, history: [], condition: condition, extra: {}
298
316
  )
299
317
  write_under_lock { |file| file.entries << entry }
300
318
  entry
@@ -323,11 +341,20 @@ module Samagotchi
323
341
  def total_limit = positive_config("schedule.max_total", 50)
324
342
 
325
343
  # One pass over the file: the entries due now, each checked for busy, then
326
- # advanced and (outside the lock) fired.
327
- # @param dry_run [Boolean] report what would fire, change nothing
344
+ # advanced and (outside the lock) fired. The due conditions run first,
345
+ # before the lock (ConditionPart); `now` moves on by the time they took.
346
+ # @param dry_run [Boolean] report what would fire, change nothing (no CMD runs)
328
347
  # @param now [Time] "now"
348
+ # @param cancelled [#call] true: stop the conditions (chi web stopping)
329
349
  # @return [Tick]
330
- def tick(dry_run: false, now: @clock.call)
350
+ def tick(dry_run: false, now: @clock.call, cancelled: -> { false })
351
+ unless dry_run
352
+ started_at = @monotonic.call
353
+ conditions = condition_results(now, cancelled)
354
+ now += @monotonic.call - started_at if conditions
355
+ # chi web stopping: no firing now, which its stop would cut short.
356
+ return Tick.new(locked: false, outcomes: []) if cancelled.call
357
+ end
331
358
  outcomes = []
332
359
  pending = []
333
360
  prune_after = []
@@ -403,6 +430,12 @@ module Samagotchi
403
430
  pending_chains = in_flight.select { |entry| entry.mode == CHAIN }.map { |entry| chain_key(links, entry) }
404
431
  due.each do |entry|
405
432
  position = updated.index { |candidate| candidate.is_a?(Entry) && candidate.id == entry.id }
433
+ gated = condition_gate(entry, links, conditions, now) unless dry_run
434
+ if gated
435
+ updated[position], outcome = gated
436
+ outcomes << outcome if outcome
437
+ next
438
+ end
406
439
  verdict = check(entry, links)
407
440
  if verdict
408
441
  kind, reason = verdict
@@ -427,7 +460,8 @@ module Samagotchi
427
460
  end
428
461
  if dry_run
429
462
  fired_chains[chain_key(links, entry)] = true if entry.mode == CHAIN
430
- outcomes << Outcome.new(id: entry.id, title: entry.title, status: "dry", detail: entry.recurrence_words, entry: entry)
463
+ detail = entry.condition.nil? ? entry.recurrence_words : "#{entry.recurrence_words} · if #{condition_cmd(entry)} (not run)"
464
+ outcomes << Outcome.new(id: entry.id, title: entry.title, status: "dry", detail: detail, entry: entry)
431
465
  next
432
466
  end
433
467
  if entry.catch_up == "none" && late?(entry, now)
@@ -524,7 +558,8 @@ module Samagotchi
524
558
  # @param strict [Boolean] a file that is not readable JSON raises rather
525
559
  # than reading as empty: a write starting from an empty list would rewrite
526
560
  # the file and lose every schedule on it. #entries stays lenient.
527
- def read(strict: false)
561
+ # @param quiet [Boolean] no log lines (the tick's condition pre-pass: its main pass logs them)
562
+ def read(strict: false, quiet: false)
528
563
  return FORMAT.read({}, collection: "schedules") unless File.exist?(path)
529
564
 
530
565
  file = FORMAT.read(JSON.parse(File.read(path)), collection: "schedules")
@@ -532,14 +567,15 @@ module Samagotchi
532
567
  if record.readable?
533
568
  Entry.from_record(record)
534
569
  else
535
- Log.warn(:worker, "schedule_entry_unreadable",
536
- id: record.raw.is_a?(Hash) ? record.raw["id"] : nil,
537
- missing: record.missing.map(&:to_s))
570
+ unless quiet
571
+ Log.warn(:worker, "schedule_entry_unreadable", id: record.raw.is_a?(Hash) ? record.raw["id"] : nil,
572
+ missing: record.missing.map(&:to_s))
573
+ end
538
574
  record
539
575
  end
540
576
  end)
541
577
  rescue JSON::ParserError, StateFormat::InvalidDocument => e
542
- Log.warn(:worker, "store_unreadable", error: e.class.name, msg: e.message)
578
+ Log.warn(:worker, "store_unreadable", error: e.class.name, msg: e.message) unless quiet
543
579
  raise Corrupt, "#{path} is not readable JSON (#{e.message}): fix or remove it before changing schedules" if strict
544
580
 
545
581
  FORMAT.read({}, collection: "schedules")
@@ -548,7 +584,9 @@ module Samagotchi
548
584
  def write(file:)
549
585
  FileUtils.mkdir_p(@store_dir)
550
586
  FileUtils.mkdir_p(@state_dir)
551
- body = FORMAT.write(file, collection: "schedules", updated_at: Time.now.utc.iso8601)
587
+ # A copy (callers keep file.entries); ConditionPart#hide_next_due.
588
+ stored = file.with(entries: file.entries.map { |entry| entry.is_a?(Entry) ? hide_next_due(entry) : entry })
589
+ body = FORMAT.write(stored, collection: "schedules", updated_at: Time.now.utc.iso8601)
552
590
  AtomicFile.write(path, "#{JSON.pretty_generate(body)}\n")
553
591
  end
554
592
 
@@ -1040,68 +1078,5 @@ module Samagotchi
1040
1078
  file.entries[position] = updated
1041
1079
  end
1042
1080
  end
1043
-
1044
- # The links behind the kept window, with the delegates that hung under
1045
- # them: archiving a link archives its descendants, and archived sessions
1046
- # are outside the retention sweep, so the delegate pile is the bulk of the
1047
- # archived count. Oldest link first, and within a link its children first
1048
- # (deepest first) and the link last. The walk stops at a link that is not
1049
- # archived, one whose subtree has a live worker, or one with a descendant
1050
- # still unarchived: nothing is deleted in that case, and the next firing
1051
- # retries (a schedule failure it is not). The anchor is never pruned:
1052
- # `last:<anchor>` must keep resolving, and it is the id the user remembers.
1053
- def prune(entry, links)
1054
- chain = []
1055
- id = entry.head
1056
- seen = []
1057
- while id && !seen.include?(id)
1058
- seen << id
1059
- chain << id
1060
- # The walk stops at the anchor: the links before it are the user's own
1061
- # history, made before this schedule existed, and the anchor itself is
1062
- # the id `last:<anchor>` and the user remember.
1063
- break if id == entry.anchor
1064
-
1065
- # The link a firing just made is not in the tick's listing; every
1066
- # older one is.
1067
- session = links.session(id) || (File.exist?(Session.session_file(id, state_dir: @state_dir)) ? Session.load(id, state_dir: @state_dir) : nil)
1068
- id = session&.continues
1069
- end
1070
- older = chain[entry.keep_links..] || []
1071
- return if older.empty?
1072
-
1073
- older.reverse_each do |link|
1074
- next if link == entry.anchor
1075
- break unless ArchiveStore.archived?(Session.session_dir(link, state_dir: @state_dir))
1076
-
1077
- tree = SessionManager.delete_tree_ids(link, @state_dir)
1078
- descendants = tree[0...-1]
1079
- # The whole subtree must be ready: a live worker anywhere in it, or a
1080
- # link's descendant that is not archived, stops the walk here rather
1081
- # than half-deleting a tree.
1082
- owned = tree.select { |sid| SessionManager.session_owner(sid, state_dir: @state_dir) }
1083
- unless owned.empty?
1084
- Log.warn(:worker, "prune_waiting", sid: link, id: entry.id, owned: owned.map { |sid| sid[0, 8] })
1085
- break
1086
- end
1087
-
1088
- open = descendants.reject { |sid| ArchiveStore.archived?(Session.session_dir(sid, state_dir: @state_dir)) }
1089
- unless open.empty?
1090
- Log.warn(:worker, "prune_open_children", sid: link, id: entry.id, open: open.map { |sid| sid[0, 8] })
1091
- break
1092
- end
1093
-
1094
- # Children first (deepest first), the link last: if a delete is
1095
- # refused partway, nothing above it has gone, so the next firing
1096
- # retries the same set instead of leaving children under a link that
1097
- # is already deleted.
1098
- SessionManager.delete_ids(tree, state_dir: @state_dir)
1099
- Log.info(:worker, "pruned_link", sid: link, id: entry.id, links: descendants.size + 1)
1100
- end
1101
- rescue SessionManager::DeleteRefused => e
1102
- Log.warn(:worker, "prune_stopped", sid: e.session_id, id: entry.id, msg: e.message)
1103
- rescue Session::NotFound => e
1104
- Log.warn(:worker, "prune_missing", id: entry.id, msg: e.message)
1105
- end
1106
1081
  end
1107
1082
  end
@@ -46,8 +46,10 @@ module Samagotchi
46
46
  module SelfProtect
47
47
  # The rules that let one agent answer chi's questions: an auto-allow
48
48
  # there is one agent approving another's, so the user decides them even
49
- # when they are listed in `guardrails.system_one.rules`.
50
- NEVER_AUTO = %w[chi-answer-piped chi-answer-http chi-broadcast].freeze
49
+ # when they are listed in `guardrails.system_one.rules`; and a
50
+ # schedule's condition (chi-schedule-if), a shell command chi's tick
51
+ # runs later, outside every gate, which only the owner sets.
52
+ NEVER_AUTO = %w[chi-answer-piped chi-answer-http chi-broadcast chi-schedule-if].freeze
51
53
  # chi's default state dir as a shell command may spell it when the
52
54
  # settings point elsewhere (the sessions and the guardrails store live
53
55
  # there).
@@ -7,7 +7,11 @@ module Samagotchi
7
7
  # Cancel a durable schedule of this session's chain by its id, a unique
8
8
  # prefix of it, or its title (docs/scheduling.md). A schedule of another
9
9
  # session's chain is refused unless the call says `all: true`: `chi
10
- # schedule cancel` is the machine-wide way.
10
+ # schedule cancel` is the machine-wide way. An entry of schedules.json
11
+ # that doesn't read (which list leaves out) goes by its exact id, as
12
+ # chi schedule cancel ID takes it: in this chain when its stored anchor
13
+ # or head is a link of it, else refused like another chain's; one whose
14
+ # chain can't be told (neither stored) only with `all: true`.
11
15
  class CancelSchedule
12
16
  NAME = ToolNames::CancelSchedule::NAME
13
17
 
@@ -23,7 +27,7 @@ module Samagotchi
23
27
  want_all = all == true || all.to_s.strip.casecmp?("true")
24
28
  schedules = Schedules.new(state_dir: peers&.state_dir)
25
29
  entry = schedules.lookup(name)
26
- return "No schedule named #{name}." if entry.nil?
30
+ return cancel_unreadable(schedules, name, want_all, peers) if entry.nil?
27
31
 
28
32
  # nil: gone since the lookup (another cancel in between).
29
33
  if want_all || peers&.session_id.nil?
@@ -43,6 +47,27 @@ module Samagotchi
43
47
  rescue StandardError => e
44
48
  "Error: #{e.message}"
45
49
  end
50
+
51
+ # @return [String] the answer for +name+ when no readable entry has it
52
+ def self.cancel_unreadable(schedules, name, want_all, peers)
53
+ raw = schedules.unreadable_record(name)
54
+ return "No schedule named #{name}." if raw.nil?
55
+
56
+ unless want_all || peers&.session_id.nil?
57
+ ends = [raw["anchor"], raw["head"]].select { |id| id.is_a?(String) && !id.empty? }
58
+ if ends.empty?
59
+ return "Error: schedule #{name} can't be read, so its chain can't be told. " \
60
+ "chi schedule cancel #{name} removes it, or say all: true if you meant it."
61
+ end
62
+ unless schedules.chain_of(peers.session_id).any? { |id| ends.include?(id) }
63
+ return "Error: #{name} belongs to another session's chain. " \
64
+ "chi schedule cancel #{name} cancels it, or say all: true if you meant it."
65
+ end
66
+ end
67
+ return "No schedule named #{name}." unless schedules.cancel(name)
68
+
69
+ "Cancelled #{name} (it couldn't be read)."
70
+ end
46
71
  end
47
72
  end
48
73
  end
@@ -334,7 +334,11 @@ module Samagotchi
334
334
  return "" unless File.file?(path)
335
335
 
336
336
  size = File.size(path)
337
- return File.read(path) if size <= truncate_at_bytes
337
+ # Valid UTF-8 (Utf8Scrub's rules, a bad byte "?" as the request's
338
+ # body has it): a command's output can hold any bytes, and the turn's
339
+ # later regex passes raise on invalid ones (the preview below is
340
+ # scrubbed too).
341
+ return File.binread(path).force_encoding(Encoding::UTF_8).scrub("?") if size <= truncate_at_bytes
338
342
 
339
343
  LogPreview.new(size, OutputGuardrails.head_tail_from_file(path: path, file_size: size, preview_bytes: preview_bytes))
340
344
  end
@@ -36,6 +36,7 @@ module Samagotchi
36
36
  flags = []
37
37
  flags << "skips #{entry.skips} of #{entry.max_skips}" if entry.skips.positive?
38
38
  flags << "disabled after #{entry.failures} failures" unless entry.enabled
39
+ flags << "if: #{ScheduleDisplay.condition_words(entry)}" unless entry.condition.nil?
39
40
  "#{entry.id} #{ScheduleDisplay.name(entry)} #{entry.target_words} #{entry.recurrence_words} " \
40
41
  "next #{entry.next_due} #{flags.join(", ")}".rstrip
41
42
  end
@@ -382,6 +382,12 @@ module Samagotchi
382
382
  file.seek(offset)
383
383
  file.read
384
384
  end
385
+ # Read binary: relabel as UTF-8 and scrub before the split (which
386
+ # raises on invalid bytes). The seek can land mid-character and a log
387
+ # can hold real binary bytes; a BINARY tail raises
388
+ # Encoding::CompatibilityError once joined with UTF-8 text (a task
389
+ # finish wake's note, task_wait's response, execute's hand-over).
390
+ content = content.force_encoding(Encoding::UTF_8).scrub
385
391
  content = content.split("\n", 2).last.to_s if offset.positive?
386
392
  content.lines.last(line_count).join
387
393
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "llm/errors"
4
+ require_relative "failure_line"
4
5
  require_relative "tools/task_runtime"
5
6
  require_relative "turn_note"
6
7
 
@@ -12,6 +13,14 @@ module Samagotchi
12
13
  # forwards each here and keeps the steps that hold the event lock or save
13
14
  # (end_turn, complete_turn, store_answer_display, record_last_turn).
14
15
  class TurnEndings
16
+ # A failed turn's error_kind when chi itself failed (FailureLine).
17
+ CHI_ERROR = FailureLine::CHI_ERROR
18
+
19
+ def self.chi_error?(error) = FailureLine.chi_error?(error)
20
+
21
+ # The one line of a failed turn (FailureLine.for).
22
+ def self.failure_line(error) = FailureLine.for(error)
23
+
15
24
  # @param failure_summary [#call] (error) → a failed turn's one line (Engine#failure_summary)
16
25
  def initialize(failure_summary:)
17
26
  @failure_summary = failure_summary
@@ -94,11 +103,12 @@ module Samagotchi
94
103
 
95
104
  steps = LLM::FailedTurn.progress(turn.session.messages, kept)
96
105
  error.kept_steps = steps if steps && error.is_a?(LLM::FailedTurn) && LLM::FailedTurn.keeps_work?(error)
97
- summary = error.respond_to?(:summary) ? error.summary : error.message
98
- TurnNote.replace_trailing(kept, TurnNote.failed(summary, continued: turn.continue, steps: steps))
106
+ TurnNote.replace_trailing(kept, TurnNote.failed(self.class.failure_line(error), continued: turn.continue, steps: steps))
99
107
  end
100
108
 
101
109
  # Called after #failed_messages, which marks the error's kept steps.
110
+ # A provider error and chi's own (.chi_error?) say their kind and their
111
+ # line (summary:); a UserError's message is its line.
102
112
  def failed_event(error, seconds)
103
113
  failed = { type: :turn_failed, error_class: error.class.name, message: error.message,
104
114
  duration_ms: (seconds * 1000).round }
@@ -108,6 +118,8 @@ module Samagotchi
108
118
  # A provider error says what kind it is, for one line per kind in the UIs.
109
119
  if error.is_a?(LLM::ProviderError)
110
120
  failed.merge!(error_kind: error.kind, retryable: error.retryable?, host: error.host, summary: failure_summary(error))
121
+ elsif self.class.chi_error?(error)
122
+ failed.merge!(error_kind: CHI_ERROR, summary: self.class.failure_line(error))
111
123
  end
112
124
  failed
113
125
  end
@@ -5,6 +5,7 @@ require_relative "output_formatter"
5
5
  require_relative "turn_note"
6
6
  require_relative "context_note"
7
7
  require_relative "llm/errors"
8
+ require_relative "failure_line"
8
9
 
9
10
  module Samagotchi
10
11
  # The state around turns a session worker (and a one-shot) keeps out of
@@ -137,7 +138,7 @@ module Samagotchi
137
138
  # model)
138
139
  # @return [Symbol] :kept or :restored
139
140
  def prompt_turn_failed(error: nil, wake: nil, wake_kept: nil, note: true)
140
- summary = error && (error.respond_to?(:summary) ? error.summary : error.message)
141
+ summary = error && FailureLine.for(error)
141
142
  steps = LLM::FailedTurn.kept_steps(error)
142
143
  @offer = nil
143
144
  if steps
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.189.0"
4
+ VERSION = "0.190.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -260,6 +260,14 @@ export function createStreamHandlers(deps) {
260
260
  // Only a rolled-back turn's line waits for its prompt_restored.
261
261
  const kept = Number.isInteger(data.kept_steps);
262
262
  liveTurn.failedText = kept ? null : text;
263
+ // A turn that failed before it began (no turn_started: the worker's
264
+ // step before the Engine's turn raised) has no turn to end: its line
265
+ // only, and the prompt_restored that follows draws it again.
266
+ if (!liveTurn.running && !kept) {
267
+ addEndBubble(text);
268
+ setLiveStatus("idle");
269
+ return;
270
+ }
263
271
  endTurnView("failed", text);
264
272
  setLiveStatus("idle");
265
273
  // A kept turn's timing line from its record, as a canceled one's and a
@@ -404,9 +404,10 @@ module Samagotchi
404
404
 
405
405
  def run_schedule_tick
406
406
  schedules = Samagotchi::Schedules.new(state_dir: @state_dir)
407
- schedules.tick(now: Time.now)
407
+ # Stopping kills a condition's CMD (its process group) and runs no more.
408
+ schedules.tick(now: Time.now, cancelled: -> { stopped? })
408
409
  # Right after the tick, so a turn-off of this tick is pushed now.
409
- publish_disabled(schedules)
410
+ retry_notices_next_scan if publish_disabled(schedules)
410
411
  rescue StandardError => e
411
412
  Log.warn(:web, "schedule_tick_failed", error: e.class.name, msg: e.message)
412
413
  ensure
@@ -418,7 +419,9 @@ module Samagotchi
418
419
 
419
420
  # Once per schedule.tick_interval_minutes: a lock-free read of
420
421
  # schedules.json (Schedules#claim_disabled_notices), so a cron tick's or
421
- # a run-now's turn-off reaches the phone within one interval.
422
+ # a run-now's turn-off reaches the phone within one interval. A claim
423
+ # that found notices but the lock held (a tick at work) is tried again
424
+ # at the next scan, not a whole interval later.
422
425
  def claim_disabled_if_due
423
426
  now = @now.call
424
427
  due = @monitor.synchronize do
@@ -427,7 +430,11 @@ module Samagotchi
427
430
  @next_notice_claim = now + (Samagotchi::Schedules.tick_interval_minutes * 60)
428
431
  true
429
432
  end
430
- publish_disabled(Samagotchi::Schedules.new(state_dir: @state_dir)) if due
433
+ retry_notices_next_scan if due && publish_disabled(Samagotchi::Schedules.new(state_dir: @state_dir))
434
+ end
435
+
436
+ def retry_notices_next_scan
437
+ @monitor.synchronize { @next_notice_claim = nil }
431
438
  end
432
439
 
433
440
  # A recurring schedule a ticker turned off by its budget (any ticker: the
@@ -438,14 +445,18 @@ module Samagotchi
438
445
  # session the schedule acts on. The claim clears each notice before it
439
446
  # is emitted: the Notifier's dedupe is per process, so two chi webs on
440
447
  # one state dir would otherwise both push it.
448
+ # @return [Boolean] true: there were notices but the lock was held
441
449
  def publish_disabled(schedules)
442
- schedules.claim_disabled_notices(now: Time.now).each do |data|
450
+ held = false
451
+ schedules.claim_disabled_notices(now: Time.now, on_lock_held: -> { held = true }).each do |data|
443
452
  @monitor.synchronize { emit("schedule_disabled", data) }
444
453
  rescue StandardError => e
445
454
  Log.warn(:web, "schedule_disabled_failed", id: data[:id], error: e.class.name, msg: e.message)
446
455
  end
456
+ held
447
457
  rescue StandardError => e
448
458
  Log.warn(:web, "schedule_notices_failed", error: e.class.name, msg: e.message)
459
+ false
449
460
  end
450
461
 
451
462
  # A change (the first look too, unless it finds nothing) is a `chi`
@@ -749,7 +749,8 @@ module Samagotchi
749
749
  # result (or the error the Engine announced as :turn_failed), the
750
750
  # answer goes to the output file and the session is saved.
751
751
  # A failure before the Engine's turn began (this save, say) goes to the
752
- # block too, with no :turn_failed: it is logged, the session idle again.
752
+ # block too: the session idle again, its :turn_failed announced
753
+ # (Engine#fail_turn_not_begun, no :turn_started before it) and logged.
753
754
  # @yieldparam result [Object, nil] Engine#run_turn's, nil on a failure
754
755
  # @yieldparam error [StandardError, nil]
755
756
  def run_engine_turn(prompt, **turn_args)
@@ -784,10 +785,11 @@ module Samagotchi
784
785
  # Still running: no turn of the Engine's ended (it never began).
785
786
  # It ends here, failed, as an Engine turn would record it: a wait
786
787
  # (ReplyWait) tells a turn's end by last_turn.
788
+ # The UIs get its :turn_failed (the line a failed turn shows) and
789
+ # the log where it raised.
787
790
  if @session.status == Session::STATUS_RUNNING
788
- @session.status = Session::STATUS_IDLE
789
- @engine.record_last_turn(@session, "failed", 0, origin, { type: :turn_failed })
790
- Log.warn(:worker, "turn_not_begun", error: e.class.name, msg: e.message)
791
+ @engine.fail_turn_not_begun(@session, e, origin: origin, turn_id: turn_args[:id])
792
+ Log.exception(:worker, "turn_not_begun", e)
791
793
  end
792
794
  ensure
793
795
  # Ended (or never begun): the saves write the session's own messages.
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: samagotchi
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.189.0
4
+ version: 0.190.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dmitry Dedov
@@ -422,6 +422,7 @@ files:
422
422
  - lib/samagotchi/event_routes.rb
423
423
  - lib/samagotchi/events.rb
424
424
  - lib/samagotchi/extension_load.rb
425
+ - lib/samagotchi/failure_line.rb
425
426
  - lib/samagotchi/file_ref.rb
426
427
  - lib/samagotchi/gem_update.rb
427
428
  - lib/samagotchi/generation_phase.rb
@@ -725,11 +726,13 @@ files:
725
726
  - lib/samagotchi/schedule_display.rb
726
727
  - lib/samagotchi/schedules.rb
727
728
  - lib/samagotchi/schedules/busy_part.rb
729
+ - lib/samagotchi/schedules/condition_part.rb
728
730
  - lib/samagotchi/schedules/edit_part.rb
729
731
  - lib/samagotchi/schedules/history_part.rb
730
732
  - lib/samagotchi/schedules/listing_part.rb
731
733
  - lib/samagotchi/schedules/notices_part.rb
732
734
  - lib/samagotchi/schedules/protection_part.rb
735
+ - lib/samagotchi/schedules/prune_part.rb
733
736
  - lib/samagotchi/schedules/recurrence.rb
734
737
  - lib/samagotchi/self_report.rb
735
738
  - lib/samagotchi/send_command.rb