samagotchi 0.183.0 → 0.184.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 (72) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +40 -1
  3. data/docs/architecture.md +11 -10
  4. data/docs/bundles.md +1 -1
  5. data/docs/configuration.md +2 -1
  6. data/docs/internals/bridge.md +1 -1
  7. data/docs/internals/bundles.md +6 -2
  8. data/docs/internals/engine.md +2 -1
  9. data/docs/internals/participants.md +1 -1
  10. data/docs/internals/prompt-caching.md +8 -1
  11. data/docs/internals/remote-sessions.md +19 -3
  12. data/docs/internals/web-frontend.md +15 -10
  13. data/docs/internals/web-push.md +11 -0
  14. data/docs/internals/working-set.md +238 -6
  15. data/docs/mcp-server.md +5 -1
  16. data/docs/memory.md +2 -1
  17. data/docs/plugins.md +6 -6
  18. data/docs/scheduling.md +14 -0
  19. data/docs/sessions.md +1 -1
  20. data/docs/thin-clients.md +29 -10
  21. data/lib/samagotchi/bridge_client.rb +12 -4
  22. data/lib/samagotchi/bundle_command/check.rb +20 -2
  23. data/lib/samagotchi/bundle_manifest.rb +5 -1
  24. data/lib/samagotchi/bundles/mcp/http_client.rb +79 -54
  25. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  26. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  27. data/lib/samagotchi/bundles/system/self_map.md +7 -2
  28. data/lib/samagotchi/engine/session.rb +14 -6
  29. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  30. data/lib/samagotchi/mcp_server/http.rb +3 -3
  31. data/lib/samagotchi/mcp_server/protocol.rb +23 -4
  32. data/lib/samagotchi/mcp_server/stdio.rb +1 -0
  33. data/lib/samagotchi/mcp_server/tools.rb +2 -1
  34. data/lib/samagotchi/model_notes.rb +34 -12
  35. data/lib/samagotchi/prompt_files.rb +11 -4
  36. data/lib/samagotchi/prompt_layout.rb +88 -0
  37. data/lib/samagotchi/prompt_part.rb +82 -20
  38. data/lib/samagotchi/reply_wait.rb +6 -3
  39. data/lib/samagotchi/schedule_command.rb +18 -4
  40. data/lib/samagotchi/schedules.rb +40 -8
  41. data/lib/samagotchi/session_access/ask.rb +53 -12
  42. data/lib/samagotchi/session_access/exchange.rb +5 -2
  43. data/lib/samagotchi/session_access/local.rb +11 -2
  44. data/lib/samagotchi/session_inbox.rb +15 -0
  45. data/lib/samagotchi/session_manager/delivery.rb +8 -4
  46. data/lib/samagotchi/system_prompt.rb +196 -161
  47. data/lib/samagotchi/tools/memory.rb +11 -3
  48. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  49. data/lib/samagotchi/version.rb +1 -1
  50. data/lib/samagotchi/web/app.rb +1 -2
  51. data/lib/samagotchi/web/ask_routes.rb +89 -19
  52. data/lib/samagotchi/web/mcp_route.rb +7 -4
  53. data/lib/samagotchi/web/public/delete_sheet.js +20 -18
  54. data/lib/samagotchi/web/public/removal_sheet_model.js +3 -4
  55. data/lib/samagotchi/web/public/running_tasks.js +0 -16
  56. data/lib/samagotchi/web/public/session_actions.js +0 -9
  57. data/lib/samagotchi/web/public/working_set_view.js +167 -21
  58. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  59. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  60. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  61. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  62. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  63. data/lib/samagotchi/web/push/notifier.rb +33 -6
  64. data/lib/samagotchi/web/server.rb +1 -1
  65. data/lib/samagotchi/web/session_hub.rb +26 -4
  66. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  67. data/lib/samagotchi/worker_link.rb +2 -2
  68. data/lib/samagotchi/working_set.rb +162 -90
  69. data/lib/samagotchi/working_set_locator.rb +221 -0
  70. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  71. data/lib/samagotchi/working_set_part.rb +281 -0
  72. metadata +6 -1
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "prompt_part"
4
+
5
+ module Samagotchi
6
+ # Where each SystemPrompt::Item of a build sits in the prompt the build
7
+ # made, worked out once beside it (SystemPrompt#prompt_parts_for): the
8
+ # place fields of its PromptPart (at, len, lead, digest, head). The
9
+ # sections are joined by "\n" (the stable ones, then the volatile ones),
10
+ # each section's items by its join; joins and the scope headings that
11
+ # belong to no item fall outside every span (a note's heading is the
12
+ # first note's lead). See docs/internals/working-set.md (Prompt parts as
13
+ # sent).
14
+ #
15
+ # The tool declarations: on a chat host they are not in the prompt (no
16
+ # place); native, inside the base text ("You have access to the following
17
+ # tools:"), whose own slice leaves them out, or, on Gemma, after the last
18
+ # section, where the prompt was rstripped before them: an item running
19
+ # into that strip is cut at it.
20
+ class PromptLayout
21
+ # What the base text says before the declarations: SystemPrompt#assist_system_prompt
22
+ # writes it from here, so the two can't drift.
23
+ TOOLS_LEAD = "You have access to the following tools:\n\n"
24
+
25
+ # @param prompt [String] the built prompt
26
+ # @param sections [Array<SystemPrompt::Section>] in prompt order
27
+ # @param declarations [String, nil] the native declarations text (nil: chat)
28
+ # @param tail [Boolean] Gemma's: the declarations follow the rstripped prompt
29
+ def initialize(prompt, sections, declarations:, tail:)
30
+ @head = PromptPart.digest_of(prompt, 16)
31
+ @spans = {}.compare_by_identity
32
+ @end = tail && declarations ? prompt.length - declarations.length : prompt.length
33
+ at = 0
34
+ sections.each do |section|
35
+ offset = at
36
+ section.items.each do |item|
37
+ @spans[item] = [offset, item.sent.length.clamp(0, [@end - offset, 0].max)]
38
+ offset += item.sent.length + section.join.length
39
+ end
40
+ at += section.text.length + 1
41
+ end
42
+ @tools = tools_span(sections, declarations, tail)
43
+ end
44
+
45
+ # Whether the declarations sit inside the base text (their chars move
46
+ # out of the base part, SystemPrompt#prompt_parts_for).
47
+ def tools_in_base? = !@tools.nil? && !@tools_tail
48
+
49
+ # The place fields of +item+'s part.
50
+ # @return [Hash]
51
+ def place(item)
52
+ at, len = @spans.fetch(item)
53
+ body = item.text
54
+ if item.kind == :base && tools_in_base?
55
+ from = @tools[0] - at - item.lead.length
56
+ body = body[0, from].to_s + body[(from + @tools[1])..].to_s
57
+ end
58
+ { at: at, len: len, lead: item.lead.length, digest: PromptPart.digest_of(body), head: @head }
59
+ end
60
+
61
+ # The tools part's place fields: none on a chat host.
62
+ # @return [Hash]
63
+ def tools_place
64
+ return {} unless @tools
65
+
66
+ { at: @tools[0], len: @tools[1], lead: 0, head: @head }
67
+ end
68
+
69
+ private
70
+
71
+ # [at, len] of the declarations in the prompt, nil when they aren't in
72
+ # it (chat) or can't be found.
73
+ def tools_span(sections, declarations, tail)
74
+ return nil unless declarations
75
+
76
+ if tail
77
+ @tools_tail = true
78
+ return [@end, declarations.length]
79
+ end
80
+
81
+ base = sections.first&.items&.first
82
+ return nil unless base&.kind == :base
83
+
84
+ index = base.text.index("#{TOOLS_LEAD}#{declarations}")
85
+ index && [@spans.fetch(base)[0] + base.lead.length + index + TOOLS_LEAD.length, declarations.length]
86
+ end
87
+ end
88
+ end
@@ -1,34 +1,64 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "digest"
3
4
  require_relative "token_usage"
4
5
 
5
6
  module Samagotchi
6
- # One part of a session's system prompt, as its size: what the session
7
- # file's `prompt_parts` records at each prompt build and the web's head view
8
- # draws (the text itself is not kept). kind: a SystemPrompt::KINDS word, or
9
- # "tools" (the tool declarations, wherever the model gets them); label: what
10
- # the row says ("AGENTS.md", "N declared"); chars: the part's length in the
11
- # prompt (a multi-item section's headings and joins are in its first part,
12
- # so a section's parts sum to its text); tokens: chars at TokenUsage's one
13
- # ratio; ref: the bare memory name (identity, notes, preloads), the file
14
- # path (agents, appended), "bundle/name" (plugins), the scope (indexes),
15
- # else nil; scope: a memory part's scope, "project" or "system" (identity:
16
- # system; a note: its own; a preload: the scope that answered), so the
17
- # page tells a project x from a system x; nil for other kinds and in a
18
- # file written before it (the page then matches by name alone).
19
- PromptPart = Data.define(:kind, :label, :chars, :tokens, :ref, :scope) do
20
- def initialize(kind:, label:, chars:, tokens:, ref: nil, scope: nil)
7
+ # One part of a session's system prompt, as its size and its place: what
8
+ # the session file's `prompt_parts` records at each prompt build and the
9
+ # web's head view draws (the text itself is not kept: the sent prompt is,
10
+ # as the session's messages[0]). kind: a SystemPrompt::KINDS word, or
11
+ # "tools" (the tool declarations, wherever the model gets them); label:
12
+ # what the row says ("AGENTS.md", "N declared"); chars: the part's length
13
+ # in the prompt (a multi-item section's headings and joins are in its
14
+ # first part, so a section's parts sum to its text); tokens: chars at
15
+ # TokenUsage's one ratio; ref: the bare memory name (identity, notes,
16
+ # preloads), the file path (agents, appended), "bundle/name" (plugins),
17
+ # the scope (indexes), else nil; scope: a memory part's scope, "project"
18
+ # or "system" (identity: system; a note: its own; a preload: the scope
19
+ # that answered), so the page tells a project x from a system x; nil for
20
+ # other kinds and in a file written before it (the page then matches by
21
+ # name alone).
22
+ #
23
+ # Where it sits in the prompt the build made (docs/internals/working-set.md,
24
+ # Prompt parts as sent), each nil in a file an older chi wrote and left
25
+ # out of #to_h when nil, as scope is:
26
+ # at: the offset its lead starts at; len: its length, lead included (NOT
27
+ # chars: a section's first part is charged its joins); lead: the lead's
28
+ # length (what chi adds before the item's own text: the "System identity
29
+ # …:" line, a note's "## name", a file's header), so the sent slice is
30
+ # head[at, len] and the item's own text head[at + lead, len - lead]. The
31
+ # tools part has one only where the declarations are in the prompt
32
+ # (native: inside the base text, whose slice leaves them out, or Gemma's
33
+ # tail); on a chat host they are a request field. digest: 12 hex of
34
+ # SHA-256 over the item's own text (as PromptNote's); head: 16 hex of
35
+ # SHA-256 of the whole built prompt, the same on every part of a build,
36
+ # so a reader knows whether a saved head is the one the parts were built
37
+ # with. params: how to fetch the item again (string keys): a memory's
38
+ # requested_scope, model_key, fallback_model_key, project_dir,
39
+ # system_dir; a file's path; the tools' [{name, chars}] (chars only where
40
+ # the renderer gives one per tool).
41
+ PromptPart = Data.define(:kind, :label, :chars, :tokens, :ref, :scope, :at, :len, :lead, :digest, :head, :params) do
42
+ def initialize(kind:, label:, chars:, tokens:, ref: nil, scope: nil, at: nil, len: nil, lead: nil, digest: nil, head: nil,
43
+ params: nil)
21
44
  super
22
45
  end
23
46
 
47
+ # The fields that say where a part sits (left out of #to_h when nil).
48
+ PLACE = %i[at len lead digest head params].freeze
49
+
24
50
  # A part of +chars+ characters, its tokens counted by the one ratio.
25
- def self.build(kind:, label:, chars:, ref: nil, scope: nil)
26
- new(kind: kind.to_s, label: label.to_s, chars: chars, tokens: tokens_for(chars), ref: ref&.to_s, scope: scope&.to_s)
51
+ def self.build(kind:, label:, chars:, ref: nil, scope: nil, **place)
52
+ new(kind: kind.to_s, label: label.to_s, chars: chars, tokens: tokens_for(chars), ref: ref&.to_s, scope: scope&.to_s,
53
+ **place.slice(*PLACE))
27
54
  end
28
55
 
29
56
  # @return [Integer] the tokens +chars+ characters count as
30
57
  def self.tokens_for(chars) = (chars / TokenUsage::CHARS_PER_TOKEN).ceil
31
58
 
59
+ # The short digests: an item's text (12 hex), the whole prompt (16).
60
+ def self.digest_of(text, size = 12) = Digest::SHA256.hexdigest(text.to_s)[0, size]
61
+
32
62
  # A saved or wire record (string or symbol keys); nil without a kind.
33
63
  def self.from_h(raw)
34
64
  return raw if raw.is_a?(PromptPart)
@@ -41,9 +71,22 @@ module Samagotchi
41
71
  chars = get.call(:chars)
42
72
  chars = chars.is_a?(Numeric) ? chars.to_i : 0
43
73
  tokens = get.call(:tokens)
74
+ int = ->(key) { get.call(key).is_a?(Integer) ? get.call(key) : nil }
75
+ text = ->(key) { get.call(key).is_a?(String) ? get.call(key) : nil }
76
+ params = get.call(:params)
44
77
  new(kind: kind, label: get.call(:label).to_s, chars: chars,
45
78
  tokens: tokens.is_a?(Numeric) ? tokens.to_i : tokens_for(chars), ref: get.call(:ref)&.to_s,
46
- scope: get.call(:scope)&.to_s)
79
+ scope: get.call(:scope)&.to_s, at: int.call(:at), len: int.call(:len), lead: int.call(:lead),
80
+ digest: text.call(:digest), head: text.call(:head), params: params.is_a?(Hash) ? stringified(params) : nil)
81
+ end
82
+
83
+ # +value+ with string keys all the way down (params as a file reads them).
84
+ def self.stringified(value)
85
+ case value
86
+ when Hash then value.to_h { |key, inner| [key.to_s, stringified(inner)] }
87
+ when Array then value.map { |inner| stringified(inner) }
88
+ else value
89
+ end
47
90
  end
48
91
 
49
92
  # The records of a saved list (others dropped).
@@ -52,11 +95,30 @@ module Samagotchi
52
95
  Array(raw).filter_map { |entry| from_h(entry) }
53
96
  end
54
97
 
55
- # The record (the wire's, the file's): without scope when it has none,
56
- # so a part that has no scope reads as an older chi wrote it.
98
+ # Each part's key, from the parts list alone (chi web's route takes it,
99
+ # the page's ws_sections.js startRows has the twin): "kind:ref" (the
100
+ # label without a ref), "@scope" when it has one, "#n" for the nth
101
+ # repeat of that in parts order (a duplicate preload: "preloads:x#2").
102
+ # spec/shared/prompt_part_keys.json holds both sides to one list.
103
+ # @param parts [Array<PromptPart, Hash>]
104
+ # @return [Array<String>]
105
+ def self.keys(parts)
106
+ seen = Hash.new(0)
107
+ list(parts).map do |part|
108
+ key = "#{part.kind}:#{part.ref || part.label}"
109
+ key = "#{key}@#{part.scope}" if part.scope
110
+ seen[key] += 1
111
+ seen[key] == 1 ? key : "#{key}##{seen[key]}"
112
+ end
113
+ end
114
+
115
+ # The record (the wire's, the file's): without scope and the place
116
+ # fields when it has none, so a part that has none reads as an older
117
+ # chi wrote it.
57
118
  def to_h
58
119
  hash = super
59
120
  hash.delete(:scope) if scope.nil?
121
+ PLACE.each { |key| hash.delete(key) if hash[key].nil? }
60
122
  hash
61
123
  end
62
124
 
@@ -196,15 +196,18 @@ module Samagotchi
196
196
  end
197
197
 
198
198
  # Whether +turn+ is a turn the caller can wait for: running now, queued
199
- # as its own turn, the last one to have ended, or an input a turn's
200
- # drain merged (its merge record: the wait follows it to that turn).
199
+ # as its own turn, the last one to have ended, one that ended with its
200
+ # reply file (SessionInbox.input_taken?'s evidence) or was settled, or
201
+ # an input a turn's drain merged (its merge record: the wait follows it
202
+ # to that turn).
201
203
  def known_turn?(session, session_dir:, turn:)
202
204
  id = turn.to_s
203
205
  return false if id.empty?
204
206
 
205
207
  running = session.status == Session::STATUS_RUNNING && session.interrupted_turn&.enqueued_id == id
206
208
  queued = SessionInbox.waiting_input(session_dir, id) == :turn_end
207
- ended = session.last_turn&.enqueued_id == id || !TurnCheckpoint.settled_turn(session_dir, id).nil?
209
+ ended = session.last_turn&.enqueued_id == id || !SessionInbox.reply_for(session_dir, id).nil? ||
210
+ !TurnCheckpoint.settled_turn(session_dir, id).nil?
208
211
  running || queued || ended || !SessionInbox.merged_into(session_dir, id).nil?
209
212
  end
210
213
 
@@ -186,7 +186,11 @@ module Samagotchi
186
186
 
187
187
  result = @schedules.tick(dry_run: @opts[:dry_run] ? true : false)
188
188
  if @opts[:format] == "json"
189
- @stdout.puts(JSON.pretty_generate({ "locked" => result.locked, "outcomes" => result.outcomes.map { |outcome| { "id" => outcome.id, "status" => outcome.status, "detail" => outcome.detail } } }))
189
+ outcomes = result.outcomes.map do |outcome|
190
+ line = { "id" => outcome.id, "status" => outcome.status, "detail" => outcome.detail }
191
+ outcome.disabled ? line.merge("disabled" => true) : line
192
+ end
193
+ @stdout.puts(JSON.pretty_generate({ "locked" => result.locked, "outcomes" => outcomes }))
190
194
  return CLI::Exit::OK
191
195
  end
192
196
 
@@ -201,7 +205,7 @@ module Samagotchi
201
205
 
202
206
  result.outcomes.each do |outcome|
203
207
  word = outcome.status == "dry" ? "would fire" : outcome.status
204
- @stdout.puts("#{outcome.id} #{word} #{outcome.detail}")
208
+ @stdout.puts("#{outcome.id} #{word} #{outcome.detail}#{" (disabled)" if outcome.disabled}")
205
209
  end
206
210
  CLI::Exit::OK
207
211
  rescue Schedules::Corrupt => e
@@ -216,7 +220,7 @@ module Samagotchi
216
220
  return failed("no schedule #{id}") if result.nil?
217
221
 
218
222
  if result.is_a?(Schedules::Outcome)
219
- @stdout.puts("#{id}: #{result.status} · #{result.detail}")
223
+ @stdout.puts("#{id}: #{result.status} · #{result.detail}#{" (disabled)" if result.disabled}")
220
224
  return result.status == "failed" ? CLI::Exit::FAILED : CLI::Exit::OK
221
225
  end
222
226
 
@@ -242,7 +246,17 @@ module Samagotchi
242
246
  def entry_line(entry)
243
247
  note = ""
244
248
  note += " skips #{entry.skips} of #{entry.max_skips} (#{skip_window(entry)})" if entry.skips.positive?
245
- note += " disabled after #{entry.failures} failures" unless entry.enabled
249
+ unless entry.enabled
250
+ note += if entry.last_result == "disabled"
251
+ " disabled"
252
+ elsif entry.skips >= entry.max_skips
253
+ " disabled after #{entry.skips} #{entry.skips == 1 ? "skip" : "skips"}"
254
+ elsif entry.failures >= entry.max_failures
255
+ " disabled after #{entry.failures} #{entry.failures == 1 ? "failure" : "failures"}"
256
+ else
257
+ " disabled"
258
+ end
259
+ end
246
260
  note += " last: #{entry.last_result}" if entry.last_result
247
261
  "#{entry.id} #{entry.mode} #{entry.recurrence_words} #{clock(entry.next_due)} #{entry.head[0, 8]}#{note}"
248
262
  end
@@ -163,9 +163,10 @@ module Samagotchi
163
163
  )
164
164
 
165
165
  # What one entry did in a tick: "fired", "skipped", "missed", "failed" or
166
- # "dry" (a --dry-run's "would fire"). +detail+ is the reason.
167
- Outcome = Data.define(:id, :title, :status, :detail, :entry) do
168
- def initialize(id:, status:, title: nil, detail: nil, entry: nil) = super
166
+ # "dry" (a --dry-run's "would fire"). +detail+ is the reason. +disabled+:
167
+ # this skip or failure used up a recurring entry's budget (#mark_disabled).
168
+ Outcome = Data.define(:id, :title, :status, :detail, :entry, :disabled, :session_id) do
169
+ def initialize(id:, status:, title: nil, detail: nil, entry: nil, disabled: false, session_id: nil) = super
169
170
  end
170
171
 
171
172
  # A whole tick.
@@ -348,6 +349,7 @@ module Samagotchi
348
349
  pending = []
349
350
  prune_after = []
350
351
  links = nil
352
+ started = []
351
353
 
352
354
  FileUtils.mkdir_p(@store_dir)
353
355
  FileUtils.mkdir_p(@state_dir)
@@ -359,7 +361,7 @@ module Samagotchi
359
361
  end
360
362
 
361
363
  file = read(strict: true)
362
- list = file.entries.grep(Entry)
364
+ list = started = file.entries.grep(Entry)
363
365
  # Ordered by the moment each entry is due, then id: with one chain
364
366
  # firing per tick, the entries of that chain take turns (a skipped
365
367
  # entry keeps its `next_due`, so the earliest waiting one goes next).
@@ -465,7 +467,7 @@ module Samagotchi
465
467
  end
466
468
  links ||= links_now unless prune_after.empty?
467
469
  prune_after.each { |entry| prune(entry, links) }
468
- Tick.new(locked: false, outcomes: outcomes)
470
+ Tick.new(locked: false, outcomes: dry_run ? outcomes : mark_disabled(outcomes, started, links: links))
469
471
  end
470
472
 
471
473
  # Fire one entry now, whatever its next_due says (`chi schedule run-now`).
@@ -515,10 +517,10 @@ module Samagotchi
515
517
  file.entries[position] = reserved
516
518
  end
517
519
 
518
- return outcome if outcome
520
+ return mark_disabled([outcome], [entry], links: links).first if outcome
519
521
  return Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: "no such schedule") unless reserved
520
522
 
521
- fire_and_record(reserved, links)
523
+ mark_disabled([fire_and_record(reserved, links)], [entry], links: links).first
522
524
  end
523
525
 
524
526
  # Minutes between the hub's ticks when schedule.auto_tick is on.
@@ -695,7 +697,9 @@ module Samagotchi
695
697
  file.entries[position] = nil
696
698
  file.entries.compact!
697
699
  else
698
- file.entries[position] = entry.with(enabled: enabled, last_result: enabled ? "enabled" : "disabled")
700
+ changed = entry.with(enabled: enabled, last_result: enabled ? "enabled" : "disabled")
701
+ # Enabled again with a fresh budget: its next skip must not end it at once.
702
+ file.entries[position] = enabled ? changed.with(skips: 0, failures: 0) : changed
699
703
  end
700
704
  end
701
705
  entry
@@ -792,6 +796,34 @@ module Samagotchi
792
796
  enabled: one_off ? false : entry.enabled)
793
797
  end
794
798
 
799
+ # The skips and failures that turned off a recurring entry that was on when
800
+ # the pass began (+before+), as the file has it now: one diff covers every
801
+ # path that records one. A `date` one-off is spent, not disabled; an entry
802
+ # off within budget is an owner's `chi schedule disable`.
803
+ def mark_disabled(outcomes, before, links: nil)
804
+ ended = outcomes.select { |outcome| %w[skipped failed].include?(outcome.status) }.map(&:id)
805
+ status_by_id = outcomes.select { |outcome| %w[skipped failed].include?(outcome.status) }
806
+ .to_h { |outcome| [outcome.id, outcome.status] }
807
+ on = before.select { |entry| entry.enabled && entry.recurrence[:kind] != "date" && ended.include?(entry.id) }.map(&:id)
808
+ return outcomes if on.empty?
809
+
810
+ off = read.entries.grep(Entry).select do |entry|
811
+ budget_reached = case status_by_id[entry.id]
812
+ when "skipped" then entry.skips >= entry.max_skips
813
+ when "failed" then entry.failures >= entry.max_failures
814
+ else false
815
+ end
816
+ on.include?(entry.id) && !entry.enabled && budget_reached
817
+ end
818
+ links ||= links_now unless off.empty?
819
+ off.each do |entry|
820
+ index = outcomes.rindex { |outcome| outcome.id == entry.id && %w[skipped failed].include?(outcome.status) }
821
+ session_id = target_of(entry, links).first || entry.head
822
+ outcomes[index] = outcomes[index].with(disabled: true, entry: entry, session_id: session_id)
823
+ end
824
+ outcomes
825
+ end
826
+
795
827
  def skipped(entry, reason)
796
828
  skips = entry.skips + 1
797
829
  disabled = skips >= entry.max_skips
@@ -8,6 +8,7 @@ require_relative "../client_id"
8
8
  require_relative "../parent_answers_command"
9
9
  require_relative "../reply_wait/target"
10
10
  require_relative "../session"
11
+ require_relative "../session_inbox"
11
12
  require_relative "../turn_flow"
12
13
  require_relative "../send_command/parent_gate"
13
14
 
@@ -34,12 +35,17 @@ module Samagotchi
34
35
  # ReplyWait::Result, +token+ for a :timeout (the next wait's).
35
36
  # #answer's: +answered_here+ false when the question was no longer
36
37
  # open (answered elsewhere first, or a newer one waits): what came
37
- # next is still waited for, as chi answer does.
38
- Reply = Data.define(:session_id, :asked, :result, :token, :answered_here) do
39
- def initialize(session_id:, asked:, result:, token:, answered_here: true) = super
38
+ # next is still waited for, as chi answer does. +rebound+: a request_id
39
+ # whose turn was already known, so nothing was sent this time (the
40
+ # first ask's turn waited on again).
41
+ Reply = Data.define(:session_id, :asked, :result, :token, :answered_here, :rebound) do
42
+ def initialize(session_id:, asked:, result:, token:, answered_here: true, rebound: false) = super
40
43
  end
41
44
 
42
- # The line ran as a session command (/model x): no reply comes.
45
+ # The line ran as a session command (/model x): no reply comes. A
46
+ # /continue yes with an offer standing (an idle session's continue
47
+ # question, its worker running) is a Reply instead: it waits on the
48
+ # continued turn (#continue_follows?).
43
49
  Ran = Data.define(:session_id)
44
50
 
45
51
  # Nothing went in. +kind+ :unknown (+error+ the resolve's
@@ -82,9 +88,17 @@ module Samagotchi
82
88
  # @param cancelled [#call, nil] true stops the wait (status :canceled);
83
89
  # before the delivery, the call (Refused :canceled). The exchange's
84
90
  # own cancelled: (the same) cuts its waits for a continue
91
+ # @param request_id [String, nil] the client's key for this ask (a
92
+ # message, never a command): its turn's enqueued id is
93
+ # SessionInbox.enqueued_id_for("ask:" + it). A turn of that id the
94
+ # session knows (running, queued, ended: ReplyWait.known_turn?) is
95
+ # waited on again, nothing sent (Reply rebound), unless it only waits
96
+ # as an input file with no worker running (#waiting_turn?); else the
97
+ # delivery carries the id, which the Bridge dedupes
85
98
  # @return [Reply, Ran, Refused]
86
99
  def call(given, prompt:, client_id:, queue:, timeout:, cap:, continuing_wait: Exchange::CONTINUING_WAIT,
87
- cancelled: nil)
100
+ cancelled: nil, request_id: nil)
101
+ enqueued_id = SessionInbox.enqueued_id_for("ask:#{request_id}") if request_id
88
102
  deadline = @clock.call + cap
89
103
  # Everything before the wait ends by here, so its MIN_SLICE fits.
90
104
  ready_by = deadline - MIN_SLICE
@@ -98,11 +112,22 @@ module Samagotchi
98
112
  return Refused.new(kind: :canceled, session_id: at.id) if cancelled&.call
99
113
 
100
114
  session = @access.show(at.id)
115
+ start = (@access.prepare_wait(at.id, session: session, turn: enqueued_id) if enqueued_id)
116
+ # A turn known only as an input file no worker reads is sent again
117
+ # (with E: the worker runs it once), so the delivery wakes one.
118
+ if start&.known_turn && (start.live || !@access.waiting_turn?(at.id, enqueued_id))
119
+ # chi send --wait --turn E's binding, queued as the first copy was
120
+ # sent (a queue never merges: no merge fallback onto another turn).
121
+ target = ReplyWait::Target.wait_only(start, requested: enqueued_id).with(queued: queue)
122
+ return wait(at, target, slice: slice(timeout, deadline), cancelled: cancelled, rebound: true)
123
+ end
124
+
101
125
  busy = @access.busy(at.id, queue: queue, session: session)
102
126
  return Refused.new(kind: :busy, session_id: at.id, busy: busy) if busy
103
127
 
104
- start = @access.prepare_wait(at.id, session: session)
105
- result = @exchange.attempt(at, prompt, client_id: client_id, queue: queue).result
128
+ start ||= @access.prepare_wait(at.id, session: session)
129
+ more = enqueued_id ? { enqueued_id: enqueued_id } : {}
130
+ result = @exchange.attempt(at, prompt, client_id: client_id, queue: queue, **more).result
106
131
  if result.continued?
107
132
  follow_until ||= [@clock.call + continuing_wait, ready_by].min
108
133
  again = @exchange.relocate(at, follow_until, bounded: true)
@@ -114,9 +139,17 @@ module Samagotchi
114
139
  next
115
140
  end
116
141
  return Refused.new(kind: :undelivered, session_id: at.id, result: result) unless result.accepted?
117
- return Ran.new(session_id: at.id) if result.command?
118
142
 
119
- return wait(at, start, result, queue: queue, slice: slice(timeout, deadline), cancelled: cancelled)
143
+ if result.command?
144
+ return Ran.new(session_id: at.id) unless continue_follows?(prompt, start)
145
+
146
+ # The continue turn runs under the offered turn's id (own_turn),
147
+ # as chi answer follows it: the worker's ack is not read.
148
+ return wait(at, ReplyWait::Target.answer(start), slice: slice(timeout, deadline), cancelled: cancelled)
149
+ end
150
+
151
+ target = @exchange.bind(start, result, queue: queue)
152
+ return wait(at, target, slice: slice(timeout, deadline), cancelled: cancelled)
120
153
  end
121
154
  end
122
155
 
@@ -220,12 +253,20 @@ module Samagotchi
220
253
 
221
254
  def answer_refused(kind, id, message) = Refused.new(kind: kind, session_id: id, message: message)
222
255
 
223
- def wait(at, start, delivered, queue:, slice:, cancelled:)
224
- target = @exchange.bind(start, delivered, queue: queue)
256
+ # A /continue yes the worker ran as a command, on a session idle with
257
+ # its continue offer standing (start's own_turn, ReplyWait.own_turn)
258
+ # and a worker running it: the offer lives only in that worker's
259
+ # memory, so with none (a new one says nothing to continue) a wait
260
+ # would hand out tokens with no end.
261
+ def continue_follows?(prompt, start)
262
+ TurnFlow.continue_yes?(prompt) && !start.running && start.live && !start.own_turn.to_s.empty?
263
+ end
264
+
265
+ def wait(at, target, slice:, cancelled:, rebound: false)
225
266
  more = cancelled ? { cancelled: cancelled } : {}
226
267
  result = @exchange.wait(at.id, target, timeout: slice, **more)
227
268
  token = Exchange::Token.dump(at.id, target) if result.status == :timeout
228
- Reply.new(session_id: at.id, asked: at.asked, result: result, token: token)
269
+ Reply.new(session_id: at.id, asked: at.asked, result: result, token: token, rebound: rebound)
229
270
  end
230
271
 
231
272
  # The wait's slice: +timeout+, cut to the time the cap leaves, never
@@ -120,8 +120,10 @@ module Samagotchi
120
120
  # takes (nil: none)
121
121
  # @param check [#call, nil] called with the session read: a refusal
122
122
  # String, or nil to go on
123
+ # @param enqueued_id [String, nil] the turn's id, the caller's (an
124
+ # ask's request_id): passed to deliver_turn only when given
123
125
  # @return [Attempted, Stopped]
124
- def attempt(target, prompt, client_id:, queue: false, cut: false, images: nil, check: nil)
126
+ def attempt(target, prompt, client_id:, queue: false, cut: false, images: nil, check: nil, enqueued_id: nil)
125
127
  id = target.id
126
128
  session = @access.show(id)
127
129
  if check && (refusal = check.call(session))
@@ -134,8 +136,9 @@ module Samagotchi
134
136
  delivery = if queue then Delivery::QUEUE
135
137
  elsif cut && running then Delivery::CUT
136
138
  end
139
+ more = enqueued_id ? { enqueued_id: enqueued_id } : {}
137
140
  result = @access.deliver_turn(id, prompt: prompt, client_id: client_id, images: refs, delivery: delivery,
138
- follow: target.via != :pinned)
141
+ follow: target.via != :pinned, **more)
139
142
  Attempted.new(target: target, session: session, owner: owner, running: running, delivery: delivery, refs: refs,
140
143
  result: result)
141
144
  end
@@ -92,6 +92,12 @@ module Samagotchi
92
92
  # @return [OwnerLock::Owner, nil] the worker or one-turn chi run that owns it
93
93
  def owner(id) = SessionManager.session_owner(id, **dir)
94
94
 
95
+ # Whether +turn+ (an enqueued id) waits as an unclaimed input file of
96
+ # session +id+ (Ask's request_id check: such a turn with no worker
97
+ # running is delivered again, which wakes one; the worker runs the id
98
+ # once). This machine's only: Remote never takes a request_id.
99
+ def waiting_turn?(id, turn) = !SessionInbox.waiting_input(session_dir(id), turn).nil?
100
+
95
101
  # SessionManager.session_rows: the SessionRows chi sessions list
96
102
  # prints and chi note --all reaches (chi web's summaries route answers
97
103
  # their #to_summary_h).
@@ -196,8 +202,11 @@ module Samagotchi
196
202
  # @param bridge [#call, nil] the worker's Bridge client (chi web's
197
203
  # live_bridge_client: POST …/ask delivers as POST …/turn does); nil:
198
204
  # SessionManager's own wait
199
- def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false, manager: nil, bridge: nil)
200
- routing = { manager: manager, bridge: bridge }.compact
205
+ # @param enqueued_id [String, nil] the turn's id (an ask's request_id's);
206
+ # nil: SessionManager mints one
207
+ def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false, manager: nil, bridge: nil,
208
+ enqueued_id: nil)
209
+ routing = { manager: manager, bridge: bridge, enqueued_id: enqueued_id }.compact
201
210
  SessionManager.deliver_turn(id, prompt: prompt, client_id: client_id, images: images, delivery: delivery,
202
211
  follow: follow, **routing, **dir)
203
212
  end
@@ -4,6 +4,7 @@ require "fileutils"
4
4
  require "json"
5
5
  require "time"
6
6
  require "securerandom"
7
+ require "digest"
7
8
  require_relative "atomic_file"
8
9
  require_relative "context_note"
9
10
  require_relative "delivery"
@@ -256,6 +257,20 @@ module Samagotchi
256
257
 
257
258
  def self.new_enqueued_id = SecureRandom.uuid
258
259
 
260
+ # The enqueued id a client's own key names (an ask's request_id): the
261
+ # same key always gives the same id, shaped as a UUID v5 (SHA-256's
262
+ # first 128 bits, the version and variant bits set), so a Bridge keeps
263
+ # it (ENQUEUED_ID_UUID) and dedupes a retry.
264
+ # @param key [String]
265
+ # @return [String]
266
+ def self.enqueued_id_for(key)
267
+ bytes = Digest::SHA256.digest(key.to_s).bytes.first(16)
268
+ bytes[6] = (bytes[6] & 0x0f) | 0x50
269
+ bytes[8] = (bytes[8] & 0x3f) | 0x80
270
+ hex = bytes.pack("C*").unpack1("H*")
271
+ "#{hex[0, 8]}-#{hex[8, 4]}-#{hex[12, 4]}-#{hex[16, 4]}-#{hex[20, 12]}"
272
+ end
273
+
259
274
  def self.valid_enqueued_id?(id) = id.is_a?(String) && ENQUEUED_ID_UUID.match?(id)
260
275
 
261
276
  def self.output_name(timestamp, enqueued_id)
@@ -176,6 +176,9 @@ module Samagotchi
176
176
  # stand-in (the web's specs); #session_owner is optional
177
177
  # @param bridge [#call, nil] returns the BridgeClient or nil; defaults to
178
178
  # the session's sidecar, waiting TURN_BRIDGE_WAIT for a new worker's
179
+ # @param enqueued_id [String, nil] the turn's id, the caller's (an ask's
180
+ # request_id: SessionInbox.enqueued_id_for), so a retry with the same
181
+ # one is the Bridge's duplicate and the file's one claim; nil mints one
179
182
  # @return [DeliverResult] :accepted (via the Bridge or a file),
180
183
  # :refused when the Bridge refused the request (any 4xx with an
181
184
  # error: bad images, a delivery it doesn't run) or a queue would reach
@@ -186,13 +189,14 @@ module Samagotchi
186
189
  # @raise [ArgumentError] no such session, or no client_id
187
190
  def deliver_turn(session_id, prompt:, client_id:, images: [], delivery: nil, no_interrupt: false,
188
191
  author: nil, pending_limit: nil, anchors: nil, follow: false, state_dir: nil, manager: self,
189
- bridge: nil)
192
+ bridge: nil, enqueued_id: nil)
190
193
  raise ArgumentError, "deliver_turn needs the sender's client_id" if client_id.to_s.empty?
191
194
 
192
195
  follow_guard(session_id, state_dir, follow) do
193
196
  deliver_turn_now(session_id, prompt: prompt, client_id: client_id, images: images, delivery: delivery,
194
197
  no_interrupt: no_interrupt, author: author, pending_limit: pending_limit,
195
- anchors: anchors, state_dir: state_dir, manager: manager, bridge: bridge)
198
+ anchors: anchors, state_dir: state_dir, manager: manager, bridge: bridge,
199
+ enqueued_id: enqueued_id)
196
200
  end
197
201
  end
198
202
 
@@ -222,7 +226,7 @@ module Samagotchi
222
226
  end
223
227
 
224
228
  private def deliver_turn_now(session_id, prompt:, client_id:, images:, delivery:, no_interrupt:, author:,
225
- pending_limit:, anchors:, state_dir:, manager:, bridge:)
229
+ pending_limit:, anchors:, state_dir:, manager:, bridge:, enqueued_id: nil)
226
230
  anchors = TurnAnchors.from(anchors)
227
231
  session_dir = Session.session_dir(session_id, state_dir: state_dir || Session.default_state_dir)
228
232
  bridge ||= lambda do
@@ -234,7 +238,7 @@ module Samagotchi
234
238
  refused = start_for_send(manager, session_id, state_dir, client_id, before: true)
235
239
  return refused if refused
236
240
 
237
- enqueued_id = SessionInbox.new_enqueued_id
241
+ enqueued_id ||= SessionInbox.new_enqueued_id
238
242
  if (client = bridge.call)
239
243
  if (missing = anchors.present.find { |anchor| !worker_has?(client, anchor.class::FEATURE) })
240
244
  return DeliverResult.new(status: :refused, code: 409, ack: missing.class::UNAVAILABLE)