samagotchi 0.161.0 → 0.162.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.
@@ -14,6 +14,8 @@ require_relative "host_registry"
14
14
  require_relative "session"
15
15
  require_relative "owner_lock"
16
16
  require_relative "bridge/card_store"
17
+ require_relative "bridge/turn_accumulator"
18
+ require_relative "bridge/turn_drawings"
17
19
  require_relative "bridge/pending_card"
18
20
  require_relative "engine"
19
21
  require_relative "turn_flow"
@@ -253,11 +255,20 @@ module Samagotchi
253
255
  end
254
256
  ArchiveStore.user_input(session.id, state_dir: Session.default_state_dir)
255
257
  sink = OneShotSink.new
258
+ # The turn's drawing, as a worker's Bridge writes it: this process is
259
+ # the session's owner (OwnerLock), the file's one writer meanwhile.
260
+ drawings = Bridge::TurnDrawings.new(path: File.join(Session.session_dir(session.id), Bridge::TurnDrawings::FILE),
261
+ messages: -> { session.messages })
262
+ accumulator = Bridge::TurnAccumulator.new(on_turn_end: drawings.method(:append))
263
+ events = lambda do |event|
264
+ sink.call(event)
265
+ accumulator.call(event)
266
+ end
256
267
  save_before_first_turn(session)
257
268
  attach_mentioned_context(session, prompt)
258
269
  max_iterations = IterationLimit.for(no_interrupt: true)
259
270
  begin
260
- result = @engine.run_turn(session, prompt, on_event: sink, max_iterations: max_iterations,
271
+ result = @engine.run_turn(session, prompt, on_event: events, max_iterations: max_iterations,
261
272
  cancel_controller: nil, images: ImageInput.extract(prompt))
262
273
  rescue LLM::ProviderError, ImageStore::Error => e
263
274
  return one_shot_failed(session, e)
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.161.0"
4
+ VERSION = "0.162.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -231,11 +231,15 @@ module Samagotchi
231
231
  # draws (the opening, steps, steers, merged lines, the empty answer):
232
232
  # a context note, a `!cmd`'s record and anything else keep today's
233
233
  # place. +origins+: each item's message index.
234
+ # One walk: +drawings+ are sorted apart by range, +origins+ never go
235
+ # back.
234
236
  def stamp_drawn(items, origins, drawings, strip:)
235
237
  return items if drawings.empty?
236
238
 
239
+ at = 0
237
240
  items.each_with_index.map do |item, i|
238
- line = drawings.find { |l| l.range.cover?(origins[i]) }
241
+ at += 1 while at < drawings.size && drawings[at].to <= origins[i]
242
+ line = drawings[at] if at < drawings.size && drawings[at].range.cover?(origins[i])
239
243
  next item unless line && drawn_kind?(item)
240
244
 
241
245
  stamped = item.merge(drawn: line.turn_id)
@@ -156,7 +156,11 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
156
156
  doc.body.append(iframe);
157
157
 
158
158
  async function load() {
159
- const texts = await Promise.all(files.map((file) => fetchFile(file)));
159
+ // Bounded too: browser fetch has no timeout, and a drop() meanwhile ends it.
160
+ const fetching = answer("fetch", true);
161
+ const texts = await Promise.race([Promise.all(files.map((file) => fetchFile(file))), fetching]);
162
+ settle((w) => w.resolve());
163
+ if (dead) throw new FrameError("the frame is gone", { dropped: true });
160
164
  const handshake = answer("load", true);
161
165
  loaded.then(() => {
162
166
  // Stop waiting on the handshake's own timer and start the code's.
@@ -145,6 +145,14 @@ function replaceById(records, record) {
145
145
  return true;
146
146
  }
147
147
 
148
+ // The record at a prompt's place among the turns that left one: a failure
149
+ // that kept nothing (its prompt went back) has no place (Bridge::TurnRanges.records).
150
+ function placedRecord(timing, index) {
151
+ const records = Array.isArray(timing?.turnRecords) ? timing.turnRecords : [];
152
+ const placed = records.filter((r) => !(r?.status === "failed" && r.failure && typeof r.failure === "object" && !r.failure.kept_steps));
153
+ return placed[index] || null;
154
+ }
155
+
148
156
  export function turnRecordAt(timing, index) {
149
157
  const records = timing?.turnRecords;
150
158
  return Array.isArray(records) ? records[index] || null : null;
@@ -257,12 +265,15 @@ export function turnGroups(items, timing, { drawings = null } = {}) {
257
265
  });
258
266
  }
259
267
 
260
- // A drawn turn's group: its record by id, its steps the drawing's gens
261
- // (the rows the working set and the footprint read, as live), its answer
262
- // the last text of a completed turn that had one, and its items (the
263
- // opening, merged lines, the empty answer) by index.
268
+ // A drawn turn's group: its record by the id its end names (`record_id`: a
269
+ // drawing chi web made from the messages pairs one as promptRecord does, by
270
+ // place for a turn saved before turn ids), else by its own id, its steps the
271
+ // drawing's gens (the rows the working set and the footprint read, as live),
272
+ // its answer the last text of a completed turn that had one, and its items
273
+ // (the opening, merged lines, the empty answer) by index.
264
274
  function drawnGroup(g, items, timing, drawing) {
265
- const record = (timing?.turnRecords || []).find((r) => r.id === g.drawn) || null;
275
+ const recordId = drawing?.end?.record_id ?? g.drawn;
276
+ const record = (timing?.turnRecords || []).find((r) => r.id === recordId) || null;
266
277
  const steps = drawingTurn(drawing).gens.map((gen, k) => ({ i: null, iteration: k + 1, thinking: gen.thinking, tools: gen.tools }));
267
278
  const last = g.texts[g.texts.length - 1];
268
279
  const answered = drawnKind(drawing.end) === "completed" && g.emptyAnswer == null && last != null && String(items[last]?.content ?? "") !== "";
@@ -296,7 +307,7 @@ function withSteers(group, steerIndexes, items) {
296
307
  // one's went back to the user, !rollback) shifts no other; a prompt saved
297
308
  // before turn ids pairs by its place among the prompts.
298
309
  function promptRecord(timing, g) {
299
- if (typeof g.turnId !== "string" || !g.turnId) return turnRecordAt(timing, g.turnIndex);
310
+ if (typeof g.turnId !== "string" || !g.turnId) return placedRecord(timing, g.turnIndex);
300
311
  return (timing?.turnRecords || []).find((r) => r.id === g.turnId) || null;
301
312
  }
302
313
 
@@ -910,7 +910,10 @@ function drawnTurnNodes(group, items, { thumbs, capabilities = {}, cards = null
910
910
  }
911
911
  const empty = kind === "completed" && (group.emptyAnswer != null || end.turn_summary?.empty_answer);
912
912
  const endNote = empty ? elementOf(emptyAnswerTemplate(group.emptyAnswer != null ? items[group.emptyAnswer] : end.turn_summary.empty_answer)) : null;
913
- const kept = view.turnEnded({ kind, endNote, turnId: end.turn_id || group.drawn }) || [];
913
+ // The answer's key (data-answer-turn: Revise, the fold) is the turn's own
914
+ // id, which a live line's end always names; a drawing made from the
915
+ // messages names none for an id it made up (m…, …~N).
916
+ const kept = view.turnEnded({ kind, endNote, turnId: end.turn_id || null }) || [];
914
917
  if (endNote && !answer.includes(endNote)) answer.push(endNote);
915
918
  // The stage's turn end: the warn cards beside the block leave with the
916
919
  // block's, after the end line.
@@ -934,7 +937,8 @@ function savedAnswer(el, group, items, kind) {
934
937
  const text = el.textContent.trim();
935
938
  const at = [group.answer, ...[...(group.texts || [])].reverse()].find((i) => i != null && String(items[i]?.content ?? "").trim() === text);
936
939
  if (at == null) return el;
937
- return nodesOf(answerBubbleTemplate(items[at], { at, turnId: kind === "completed" ? group.turnId : null })).firstElementChild;
940
+ const turnId = kind === "completed" ? group.drawing?.end?.turn_id || null : null;
941
+ return nodesOf(answerBubbleTemplate(items[at], { at, turnId })).firstElementChild;
938
942
  }
939
943
 
940
944
  // The steps' texts paired with the turn's saved texts in order: each its
@@ -200,8 +200,10 @@ export function drawWalk(walk, doc = document) {
200
200
  fork.append(el(doc, "span", "eyebrow", "Which case?"));
201
201
  for (const c of cases) {
202
202
  const b = button(doc, "ww-case");
203
- b.append(el(doc, "span", null, c.when), el(doc, "span", "ww-case-to", c.to != null ? `step ${c.to + 1} →` : "?"));
204
- b.disabled = c.to == null;
203
+ // A case back to its own step (a retry, as models write it) has nowhere to go.
204
+ const here = c.to === k;
205
+ b.append(el(doc, "span", null, c.when), el(doc, "span", "ww-case-to", here ? "this step" : c.to != null ? `step ${c.to + 1} →` : "?"));
206
+ b.disabled = c.to == null || here;
205
207
  b.addEventListener("click", () => { walker.go(c.to); render(); });
206
208
  for (const [type, on] of [["mouseenter", true], ["mouseleave", false], ["focus", true], ["blur", false]]) {
207
209
  b.addEventListener(type, () => peek(c.to, on));
@@ -76,7 +76,13 @@ module Samagotchi
76
76
  # A live worker from before turn drawings lists no of_turn on its
77
77
  # cards: its turns all draw as before.
78
78
  drawings = parts && req.params["drawings"] == "1" && (!live || worker_draws?(id))
79
- drawn = drawings ? drawn_lines(id, raw_messages) : []
79
+ raw_cards = live_or_saved(turn_snapshot, "cards") { saved_cards(id, messages: raw_messages) }
80
+ drawn = if drawings
81
+ drawn_lines(id, raw_messages, timing: timing, entries: raw_cards, cwd: session.working_directory,
82
+ skip_turn_id: current_turn.is_a?(Hash) ? current_turn["turn_id"] : nil)
83
+ else
84
+ []
85
+ end
80
86
  messages = messages_for_display(raw_messages, parts: parts, cwd: session.working_directory,
81
87
  drawings: drawn, strip_drawn: true)
82
88
  json_response(200, {
@@ -100,7 +106,7 @@ module Samagotchi
100
106
  plugin_warning: turn_snapshot && turn_snapshot["plugin_warning"],
101
107
  # Plugins' slow setup still running (chi.init): the page's init row.
102
108
  init_tasks: snapshot_list(turn_snapshot, "init_tasks"),
103
- cards: cards_for_display(live_or_saved(turn_snapshot, "cards") { saved_cards(id, messages: raw_messages) }, cwd: session.working_directory),
109
+ cards: cards_for_display(raw_cards, cwd: session.working_directory),
104
110
  # The composer's / autocomplete; the built-ins until a worker
105
111
  # names its plugins' too.
106
112
  commands: turn_snapshot&.fetch("commands", nil) || SessionCommands.builtin_registry.listing,
@@ -147,14 +153,19 @@ module Samagotchi
147
153
  link.live? && Array(link.sidecar.features).include?(Bridge::TurnDrawings::FEATURE)
148
154
  end
149
155
 
150
- # The session's turn drawings that hold against +messages+ (the live
151
- # snapshot's, else the file's): Bridge::TurnDrawings, cached by the
152
- # file's size and mtime; the newest SHOWN_MAX of them.
153
- # A drawing that can't be read draws its turn as before.
154
- def drawn_lines(id, messages)
155
- Degrade.call(:web, "turn_drawings_unreadable", fallback: []) do
156
- dir = @session_class.session_dir(id, state_dir: default_state_dir)
157
- Bridge::TurnDrawings.valid(Bridge::TurnDrawings.read(dir), messages).last(Bridge::TurnDrawings::SHOWN_MAX)
156
+ # The lines the show draws +messages+' turns from (the live snapshot's
157
+ # messages, else the file's), one per finished turn:
158
+ # Bridge::TurnDrawings.cover over the session's file (.read, cached by
159
+ # its size and mtime), the turns no line covers made from their
160
+ # messages with the show's +timing+ records and CardStore +entries+.
161
+ # A file that can't be read gives no lines: every turn is made. Should
162
+ # the cover itself fail, the show draws its turns as before (no line).
163
+ def drawn_lines(id, messages, timing:, entries:, cwd:, skip_turn_id:)
164
+ dir = @session_class.session_dir(id, state_dir: default_state_dir)
165
+ lines = Degrade.call(:web, "turn_drawings_unreadable", fallback: []) { Bridge::TurnDrawings.read(dir) }
166
+ Degrade.call(:web, "turn_drawings_uncovered", fallback: []) do
167
+ Bridge::TurnDrawings.cover(lines, messages, timing: timing, entries: entries, skip_turn_id: skip_turn_id,
168
+ session_id: id, cwd: cwd)
158
169
  end
159
170
  end
160
171
 
@@ -162,7 +173,7 @@ module Samagotchi
162
173
  # (chi web's one unfold of a drawing, its cards too); nothing without
163
174
  # one.
164
175
  def turn_drawings_field(lines, messages)
165
- stamped = messages.filter_map { |item| item[:drawn] }.uniq
176
+ stamped = messages.to_set { |item| item[:drawn] }
166
177
  shown = lines.select { |line| stamped.include?(line.turn_id) }
167
178
  return {} if shown.empty?
168
179
 
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.161.0
4
+ version: 0.162.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dmitry Dedov
@@ -206,7 +206,9 @@ files:
206
206
  - lib/samagotchi/bridge/sse_writer.rb
207
207
  - lib/samagotchi/bridge/turn_accumulator.rb
208
208
  - lib/samagotchi/bridge/turn_drawings.rb
209
+ - lib/samagotchi/bridge/turn_drawings/synth.rb
209
210
  - lib/samagotchi/bridge/turn_notice.rb
211
+ - lib/samagotchi/bridge/turn_ranges.rb
210
212
  - lib/samagotchi/bridge_client.rb
211
213
  - lib/samagotchi/bridge_client/event_stream.rb
212
214
  - lib/samagotchi/bridge_client/sse_parser.rb