samagotchi 0.177.0 → 0.178.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 (88) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -1
  3. data/docs/architecture.md +5 -4
  4. data/docs/cli.md +31 -6
  5. data/docs/guardrails.md +1 -1
  6. data/docs/internals/background-tasks.md +23 -2
  7. data/docs/internals/bridge.md +17 -6
  8. data/docs/internals/bundles.md +4 -3
  9. data/docs/internals/participants.md +8 -5
  10. data/docs/internals/remote-sessions.md +6 -1
  11. data/docs/internals/session-lifecycle.md +176 -0
  12. data/docs/internals/web-frontend.md +14 -6
  13. data/docs/internals/working-set.md +33 -6
  14. data/docs/plugins.md +1 -1
  15. data/docs/releasing.md +3 -2
  16. data/docs/scheduling.md +8 -1
  17. data/docs/sessions.md +15 -9
  18. data/docs/testing.md +4 -2
  19. data/lib/samagotchi/bridge/card_store.rb +2 -19
  20. data/lib/samagotchi/bridge.rb +38 -6
  21. data/lib/samagotchi/bundle_command/check.rb +1 -1
  22. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  23. data/lib/samagotchi/compat.rb +0 -7
  24. data/lib/samagotchi/engine/events.rb +43 -0
  25. data/lib/samagotchi/engine/session.rb +7 -0
  26. data/lib/samagotchi/engine.rb +9 -3
  27. data/lib/samagotchi/event_fanout.rb +56 -0
  28. data/lib/samagotchi/guardrails/approvals.rb +0 -4
  29. data/lib/samagotchi/memory_bundle/shipped_update.rb +1 -1
  30. data/lib/samagotchi/note_delivery.rb +9 -4
  31. data/lib/samagotchi/plugin/sessions.rb +2 -1
  32. data/lib/samagotchi/revise_anchor.rb +2 -0
  33. data/lib/samagotchi/schedules.rb +12 -5
  34. data/lib/samagotchi/session_access/contract.rb +4 -0
  35. data/lib/samagotchi/session_access/local.rb +16 -4
  36. data/lib/samagotchi/session_access/remote.rb +42 -9
  37. data/lib/samagotchi/session_archive_command.rb +38 -10
  38. data/lib/samagotchi/session_chain/delete.rb +98 -25
  39. data/lib/samagotchi/session_chain/delete_preview.rb +2 -2
  40. data/lib/samagotchi/session_delete_command.rb +33 -10
  41. data/lib/samagotchi/session_inbox.rb +29 -0
  42. data/lib/samagotchi/session_inbox_delivery.rb +13 -5
  43. data/lib/samagotchi/session_lifecycle/allowed.rb +69 -0
  44. data/lib/samagotchi/session_lifecycle/canonical.rb +49 -0
  45. data/lib/samagotchi/session_lifecycle/reading.rb +65 -0
  46. data/lib/samagotchi/session_lifecycle.rb +59 -0
  47. data/lib/samagotchi/session_manager/delivery.rb +29 -6
  48. data/lib/samagotchi/session_manager/lifecycle.rb +33 -39
  49. data/lib/samagotchi/session_manager/removal.rb +117 -25
  50. data/lib/samagotchi/session_manager/running_tasks.rb +334 -0
  51. data/lib/samagotchi/session_manager/spawn.rb +2 -2
  52. data/lib/samagotchi/sessions_command.rb +1 -1
  53. data/lib/samagotchi/system_prompt.rb +22 -2
  54. data/lib/samagotchi/task_files.rb +37 -4
  55. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +7 -1
  56. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  57. data/lib/samagotchi/terminal_ui/local_link.rb +11 -3
  58. data/lib/samagotchi/tool_names.rb +1 -1
  59. data/lib/samagotchi/tools/memory.rb +29 -0
  60. data/lib/samagotchi/tools/task_runtime.rb +25 -6
  61. data/lib/samagotchi/turn_anchors.rb +5 -0
  62. data/lib/samagotchi/verify_anchor.rb +2 -0
  63. data/lib/samagotchi/version.rb +1 -1
  64. data/lib/samagotchi/web/app.rb +5 -1
  65. data/lib/samagotchi/web/participant_show.rb +3 -4
  66. data/lib/samagotchi/web/participant_view.rb +4 -6
  67. data/lib/samagotchi/web/public/data.js +19 -3
  68. data/lib/samagotchi/web/public/delete_sheet.js +67 -11
  69. data/lib/samagotchi/web/public/running_tasks.js +73 -0
  70. data/lib/samagotchi/web/public/session_actions.js +57 -8
  71. data/lib/samagotchi/web/public/stop_sheet.js +3 -2
  72. data/lib/samagotchi/web/public/working_set.js +3 -28
  73. data/lib/samagotchi/web/public/working_set_view.js +5 -2
  74. data/lib/samagotchi/web/public/ws_item_sig.js +51 -0
  75. data/lib/samagotchi/web/public/ws_peek.js +23 -13
  76. data/lib/samagotchi/web/public/ws_reader.js +22 -12
  77. data/lib/samagotchi/web/public/ws_sections.js +1 -0
  78. data/lib/samagotchi/web/public/ws_timeline.js +9 -6
  79. data/lib/samagotchi/web/session_control.rb +66 -16
  80. data/lib/samagotchi/web/session_summary.rb +7 -0
  81. data/lib/samagotchi/web/working_set_routes.rb +29 -8
  82. data/lib/samagotchi/worker_boot.rb +9 -6
  83. data/lib/samagotchi/worker_link.rb +9 -1
  84. data/lib/samagotchi/worker_presence.rb +4 -0
  85. data/lib/samagotchi/working_set.rb +26 -0
  86. data/lib/samagotchi/working_set_command.rb +10 -7
  87. data/lib/samagotchi/working_set_steer.rb +3 -10
  88. metadata +9 -1
@@ -480,7 +480,8 @@ module Samagotchi
480
480
  # {status: "restarted", session_id, from_version, version} (version nil:
481
481
  # the new worker is still starting; its bridge_up follows); 409
482
482
  # {error: "held" | "not_running" | "unsupported" | "failed", reason, detail} in words (a stopped
483
- # worker: held, reason stopped, its pid); 409
483
+ # worker: held, reason stopped, its pid; a stop marked: held, reason stop_marked;
484
+ # deleting: held, reason deleting); 409
484
485
  # owned_by_tui; 404.
485
486
  def handle_restart(_req, id)
486
487
  result = @manager.restart_session(id, state_dir: @state_dir, client_id: ClientId::WEB_RESTART)
@@ -498,12 +499,17 @@ module Samagotchi
498
499
  # POST /api/sessions/:id/archive: hide it (and its delegates) from the
499
500
  # lists, keep it for good. A live idle worker is stopped first; a turn
500
501
  # running in it or a delegate, a one-turn chi run's session and a scratch one
501
- # are refused (409).
502
- def handle_archive(_req, id)
503
- result = @manager.archive_session(id, state_dir: @state_dir, wait: STOP_WAIT_SECONDS)
502
+ # are refused (409). Background tasks it or a delegate started that
503
+ # still run: 409 tasks_running, unless the body says {stop_tasks: true}
504
+ # (then stopped first; the 200 names them, #task_fields).
505
+ def handle_archive(req, id)
506
+ body = parse_json(request_body(req, 4096))
507
+ result = @manager.archive_session(id, state_dir: @state_dir, wait: STOP_WAIT_SECONDS,
508
+ running_tasks: running_tasks_policy(body.is_a?(Hash) && body["stop_tasks"]))
504
509
  (result.archived + result.discarded).each { |sid| @hub&.touch(sid) }
505
510
  json_response(200, { status: "archived", session_id: result.id, archived: result.archived,
506
- stopped: result.stopped, discarded: result.discarded })
511
+ stopped: result.stopped, discarded: result.discarded,
512
+ **task_fields(result.to_h) })
507
513
  rescue SessionManager::OwnedByTUI => e
508
514
  owned_by_one_shot(id, e)
509
515
  rescue SessionManager::ArchiveRefused => e
@@ -521,29 +527,36 @@ module Samagotchi
521
527
  # force a live worker is stopped first (the page sends it: its confirm
522
528
  # says so); without it a live worker's session is refused, 409
523
529
  # worker_running, as chi sessions delete without --force. A one-turn chi run's
524
- # session is always refused.
530
+ # session is always refused. Background tasks the delete's sessions
531
+ # started that still run: 409 tasks_running, unless ?stop_tasks=true
532
+ # (then stopped first; the 200 names them, #task_fields).
525
533
  def handle_delete(req, id)
526
534
  result = @manager.delete_session(id, state_dir: @state_dir, stop: truthy_param?(req.GET["force"]),
527
- wait: STOP_WAIT_SECONDS, revive_previous: true, refuse_continuing: true)
535
+ wait: STOP_WAIT_SECONDS, revive_previous: true, refuse_continuing: true,
536
+ expect: req.GET["expect"],
537
+ running_tasks: running_tasks_policy(req.GET["stop_tasks"]))
528
538
  touch_deleted(result[:id], result)
529
539
  json_response(200, { status: "deleted", session_id: result[:id], stopped: result[:stopped],
530
540
  unarchived: Array(result[:unarchived]), moved_back: Array(result[:moved_back]),
531
- deleted: Array(result[:deleted] || [result[:id]]), left_running: Array(result[:left_running]) })
541
+ deleted: Array(result[:deleted] || [result[:id]]), left_running: Array(result[:left_running]),
542
+ **task_fields(result) })
532
543
  rescue SessionManager::OwnedByTUI => e
533
544
  owned_by_one_shot(id, e)
534
545
  rescue SessionManager::DeleteRefused => e
535
546
  delete_refused(e)
536
547
  end
537
548
 
538
- # DELETE /api/sessions/:id/chain?force=: every link of the chain with
539
- # their delegates (SessionManager.delete_chain). Query-only.
549
+ # DELETE /api/sessions/:id/chain?force=&stop_tasks=: every link of the
550
+ # chain with their delegates (SessionManager.delete_chain). Query-only.
540
551
  def handle_delete_chain(req, id)
541
552
  result = @manager.delete_chain(id, state_dir: @state_dir, stop: truthy_param?(req.GET["force"]),
542
- wait: STOP_WAIT_SECONDS)
553
+ wait: STOP_WAIT_SECONDS, expect: req.GET["expect"],
554
+ running_tasks: running_tasks_policy(req.GET["stop_tasks"]))
543
555
  touch_deleted(id, result)
544
556
  json_response(200, { status: "deleted", session_id: id, deleted: result[:deleted], left: result[:left],
545
557
  left_running: result[:left_running], unarchived: result[:unarchived],
546
- stopped: result[:stopped], cut_off: result[:cut_off], refusal: result[:refusal] })
558
+ stopped: result[:stopped], cut_off: result[:cut_off], refusal: result[:refusal],
559
+ **task_fields(result) })
547
560
  rescue SessionManager::OwnedByTUI => e
548
561
  owned_by_one_shot(e.session_id, e)
549
562
  rescue SessionManager::DeleteRefused => e
@@ -572,9 +585,34 @@ module Samagotchi
572
585
  ids.compact.uniq.each { |sid| @hub.touch(sid) }
573
586
  end
574
587
 
588
+ # A user's delete or archive: refused on running tasks (REFUSE), or,
589
+ # asked to (+stop_tasks+: the page's second confirm, --stop-tasks),
590
+ # stopped by "user".
591
+ def running_tasks_policy(stop_tasks)
592
+ policies = SessionManager::RunningTasks::Policy
593
+ truthy_param?(stop_tasks) ? policies.stop(by: "user") : policies::REFUSE
594
+ end
595
+
596
+ # The 200's tasks_stopped, tasks_not_stopped and tasks_ended (each
597
+ # [{session_id, id, command}], empty unless the tasks were stopped).
598
+ def task_fields(result)
599
+ %i[tasks_stopped tasks_not_stopped tasks_ended].to_h { |key| [key, Array(result[key]).map(&:to_wire)] }
600
+ end
601
+
602
+ # The 409 tasks_running's own fields: +op+ ("delete" or "archive"),
603
+ # the tasks ({running, unverified, unreadable}), whether the worker
604
+ # was stopped, a chain's links (the words name them).
605
+ def tasks_running_fields(error, op)
606
+ links = error.respond_to?(:links) ? error.links : []
607
+ { op: op, tasks: error.tasks.to_wire, worker_stopped: error.worker_stopped, stopped_worker: error.stopped_worker,
608
+ links: (links unless links.empty?) }
609
+ end
610
+
575
611
  # 409 with the refusal's reason as its code, and what a remote client
576
- # raises it again from (ids, the schedule).
612
+ # raises it again from (ids, the schedule; tasks_running's tasks).
577
613
  def delete_refused(error)
614
+ return delete_tasks_refused(error) if error.reason == :tasks_running
615
+
578
616
  detail = error.reason == :still_stopping ? "#{error.message}; try again in a moment" : error.message
579
617
  # A moved delegate that can't go back: whether the page can stop it
580
618
  # (its "Stop its worker, then delete"), as the refusal saw it.
@@ -587,6 +625,11 @@ module Samagotchi
587
625
  schedule_id: error.schedule_id, stoppable: stoppable)
588
626
  end
589
627
 
628
+ def delete_tasks_refused(error)
629
+ refusal_response(409, "tasks_running", error, session_id: error.session_id, reason: "tasks_running",
630
+ **tasks_running_fields(error, "delete"))
631
+ end
632
+
590
633
  # 409 owned_by_tui in the words a refused archive, delete or continue
591
634
  # shows (stop, restart, a turn and a command show OwnedByTUI's own).
592
635
  def owned_by_one_shot(id, error = nil)
@@ -603,10 +646,17 @@ module Samagotchi
603
646
  refusal_response(409, "owned_by_tui", error, session_id: error.session_id, scratch: scratch)
604
647
  end
605
648
 
606
- # 409 scratch or busy (every other reason: a turn, a queued prompt, an
607
- # open step-limit question, in it or a delegate, +busy_id+), with the
608
- # reason for a remote client.
649
+ # 409 scratch, tasks_running (#tasks_running_fields) or busy (every
650
+ # other reason: a turn, a queued prompt, an open step-limit question,
651
+ # in it or a delegate, +busy_id+), with the reason for a remote client.
652
+ # tasks_running, not busy: an older chi --remote then says chi web's
653
+ # words, not "a turn is running".
609
654
  def archive_refused(error)
655
+ if error.reason == :tasks_running
656
+ return refusal_response(409, "tasks_running", error, session_id: error.session_id, reason: "tasks_running",
657
+ **tasks_running_fields(error, "archive"))
658
+ end
659
+
610
660
  refusal_response(409, error.reason == :scratch ? "scratch" : "busy", error, session_id: error.session_id,
611
661
  reason: error.reason.to_s, busy_id: error.busy_id)
612
662
  end
@@ -166,6 +166,13 @@ module Samagotchi
166
166
  session.displayed_status(owner: owner)
167
167
  end
168
168
 
169
+ def shown_status(session, state, turn_snapshot, owner:)
170
+ status = displayed_status(session, state, owner: owner)
171
+ return Session::STATUS_IDLE if status == Session::STATUS_RUNNING && turn_snapshot && !turn_snapshot["current_turn"]
172
+
173
+ status
174
+ end
175
+
169
176
  def first_preview_for(session)
170
177
  raw = session.first_preview || session.last_prompt || ""
171
178
  norm = raw.to_s.gsub(/\s+/, " ").strip
@@ -1,9 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "uri"
3
4
  require_relative "../working_set"
4
5
  require_relative "../llm_context_view"
5
6
  require_relative "../session_setting"
6
7
  require_relative "../memory_paths"
8
+ require_relative "../worker_link"
7
9
  require_relative "participant_view"
8
10
 
9
11
  module Samagotchi
@@ -43,26 +45,45 @@ module Samagotchi
43
45
  json_response(200, shown.merge("running" => set[:running] == true))
44
46
  end
45
47
 
46
- # GET /api/sessions/:id/working_set/item?kind=&key=[&now=1]: what the
48
+ # GET /api/sessions/:id/working_set/item?kind=&key=[&now=1][&latest=1]: what the
47
49
  # model has of one item, its timeline (WorkingSet.timeline_of: every
48
50
  # run of it, in conversation order), the reader's and the popover
49
- # peek's. Owner only. Always built from messages, unlike the set's
50
- # route: the worker's snapshot messages (they lag a running turn's
51
- # events; the page asks again on its next :working_set_updated), else
51
+ # peek's. Owner only. A live worker with the feature
52
+ # (WorkingSet::ITEM_FEATURE) answers just the item (the Bridge's GET
53
+ # working_set/item: the running turn's view mid-turn, with at and
54
+ # running), passed on as is: no snapshot, no session file; no answer
55
+ # or a failed one is a 502 (the page asks again). Otherwise, or on a
56
+ # 404 (no such route), it is built from messages: an older
57
+ # worker's snapshot messages (they lag a running turn's events), else
52
58
  # the file's. Whole texts: the tool limits bound them (read's
53
59
  # truncate_at_bytes, the ToolRunner cap). +now+ (a memory): what its
54
60
  # latest read would answer now and the diff (WorkingSet.memory_now).
61
+ # +latest+ (the peek): only the events it draws and the counts
62
+ # (WorkingSet::Timeline#peek_h).
55
63
  def handle_working_set_item(req, id)
56
64
  kind = req.GET["kind"].to_s
57
65
  key = req.GET["key"].to_s
58
- unless [WorkingSet::FILE, WorkingSet::MEMORY, WorkingSet::URL].include?(kind) && !key.strip.empty?
59
- return error_response(400, "invalid_item", "expected kind (file, memory or url) and key")
66
+ return error_response(400, "invalid_item", WorkingSet::INVALID_ITEM) unless WorkingSet::KINDS.include?(kind) && !key.strip.empty?
67
+
68
+ latest = req.GET["latest"] == "1"
69
+ features = WorkerLink.live_features(id, state_dir: default_state_dir)
70
+ if Array(features).include?(WorkingSet::ITEM_FEATURE)
71
+ query = { kind: kind, key: key }
72
+ query[:now] = "1" if req.GET["now"] == "1"
73
+ query[:latest] = "1" if latest
74
+ status, answer = bridge_get(id, "working_set/item?#{URI.encode_www_form(query)}")
75
+ return json_response(200, answer) if status == 200 && answer.is_a?(Hash)
76
+ # No answer, or a failed one: the page marks its ask failed and asks again at the next event, rather than
77
+ # drawing an older worker's lagging messages it would never ask again for. Only a 404 (no such route) falls back.
78
+ unless status == 404
79
+ return error_response(502, "bridge_error", "the session's worker didn't answer the item (#{status || "no reply"})")
80
+ end
60
81
  end
61
82
 
62
83
  session = @session_class.load(id, state_dir: default_state_dir)
63
- source = working_set_source(bridge_get_json(id, "snapshot"), session)
84
+ source = working_set_source(features && bridge_get_json(id, "snapshot"), session)
64
85
  timeline = WorkingSet.timeline_of(source.messages, kind: kind, key: key, strategy: source.strategy, cwd: source.cwd)
65
- body = timeline.to_h
86
+ body = latest ? timeline.peek_h : timeline.to_h
66
87
  if req.GET["now"] == "1" && kind == WorkingSet::MEMORY
67
88
  body[:now] = WorkingSet.memory_now(source.messages, key: key, strategy: source.strategy, cwd: source.cwd,
68
89
  root: MemoryPaths.system_dir)&.to_h
@@ -165,14 +165,17 @@ module Samagotchi
165
165
  end
166
166
 
167
167
  # Delete a session its worker left empty. Checked again now the lock is
168
- # free: a note or input may have come in since the worker looked, and a
169
- # worker woken meanwhile owns it (delete_session refuses). A `chi send`
170
- # landing between this check and the delete fails with "no session"
171
- # (a window of an empty session's last moments, left as is).
168
+ # free, and once more under the deleting lock (delete_session's
169
+ # still:): a note or input may have come in since the worker looked
170
+ # (one that went in before the lock keeps the session), and a worker
171
+ # woken meanwhile owns it (delete_session refuses). A delivery during
172
+ # the deleting lock is refused (DeliverResult::DELETING, its file taken
173
+ # back), one after removal finds no session.
172
174
  private def discard_left_session(session_id, state_dir:, default_model:)
173
- return unless SessionManager.discardable?(session_id, state_dir: state_dir, default_model: default_model)
175
+ empty = -> { SessionManager.discardable?(session_id, state_dir: state_dir, default_model: default_model) }
176
+ return unless empty.call
174
177
 
175
- SessionManager.delete_session(session_id, state_dir: state_dir, purge_runs: false)
178
+ SessionManager.delete_session(session_id, state_dir: state_dir, purge_runs: false, still: empty)
176
179
  Log.info(:worker, "discarded_empty", sid: session_id)
177
180
  rescue SessionManager::DeleteRefused, SessionManager::OwnedByTUI, ArgumentError, SystemCallError => e
178
181
  Log.info(:worker, "kept_session", sid: session_id, error: e.class.name, msg: e.message)
@@ -109,11 +109,19 @@ module Samagotchi
109
109
  def live? = false
110
110
  def worker_owned? = true
111
111
 
112
+ def short_message(via: ChiInvocation::HERE)
113
+ "its worker runs a newer chi: #{remedy(via)}"
114
+ end
115
+
112
116
  def message(session_id, via: ChiInvocation::HERE)
113
117
  "session #{session_id}'s worker runs chi #{sidecar.version || "?"} (protocol #{sidecar.protocol}), " \
114
118
  "newer than this chi #{Samagotchi::VERSION} (protocol #{PROTOCOL}): restart " \
115
- "#{via.remote? ? via.web : "chi web"} or update this chi"
119
+ "#{remedy(via)}"
116
120
  end
121
+
122
+ private
123
+
124
+ def remedy(via) = "restart #{via.remote? ? via.web : "chi web"} or update this chi"
117
125
  end
118
126
 
119
127
  module_function
@@ -78,6 +78,10 @@ module Samagotchi
78
78
  # nothing else may resume, stop or delete it.
79
79
  def tui_owned? = owner&.tui? == true
80
80
 
81
+ # A deleter holds it (OwnerLock kind deleting: SessionManager's
82
+ # delete, an empty session's discard) while the session's files go.
83
+ def deleting? = owner&.deleting? == true
84
+
81
85
  # The `<id>/stopped` marker: a user's stop, not the turn's status.
82
86
  def stop_marked? = stop_marked
83
87
 
@@ -37,6 +37,13 @@ module Samagotchi
37
37
  FILE = "file"
38
38
  MEMORY = "memory"
39
39
  URL = "url"
40
+ KINDS = [FILE, MEMORY, URL].freeze
41
+ # An item route's refusal of a kind not in KINDS or a blank key (chi
42
+ # web's and the Bridge's alike).
43
+ INVALID_ITEM = "expected kind (file, memory or url) and key"
44
+ # The Bridge feature: GET working_set/item answers one item's timeline
45
+ # from the worker (the running turn's view mid-turn).
46
+ ITEM_FEATURE = "working_set_item"
40
47
  LIVE = "live"
41
48
  STALE = "stale"
42
49
  FORGOTTEN = "forgotten"
@@ -245,7 +252,26 @@ module Samagotchi
245
252
  # (the reader shows them newest first).
246
253
  Timeline = Data.define(:kind, :key, :events) do
247
254
  def to_h = { kind: kind, key: key, events: events.map(&:to_h) }
255
+
256
+ # The peek's answer (the route's latest=1): only the events the
257
+ # page's peek draws (ws_timeline.js peekOf, ported: the latest edit or
258
+ # write with a diff and the newest event after it, else the newest
259
+ # run that isn't one, else the newest), and the counts of its "N reads,
260
+ # M edits" (countsText). peekOf over these picks what it picks over all.
261
+ def peek_h
262
+ edit_at = events.rindex { |e| PEEK_EDITS.include?(e.op) && e.diff }
263
+ shown = if edit_at
264
+ [events[edit_at], events[(edit_at + 1)..].last].compact
265
+ else
266
+ [events.reverse.find { |e| !PEEK_EDITS.include?(e.op) } || events.last].compact
267
+ end
268
+ counts = { read: events.count { |e| COUNT_READS.include?(e.op) }, edit: events.count { |e| COUNT_EDITS.include?(e.op) } }
269
+ { kind: kind, key: key, events: shown.map(&:to_h), counts: counts, latest: true }
270
+ end
248
271
  end
272
+ PEEK_EDITS = %w[edit write].freeze
273
+ COUNT_READS = %w[read memory_read fetch].freeze
274
+ COUNT_EDITS = %w[edit write memory_write].freeze
249
275
 
250
276
  # A stale memory's text now against what the model has: the +text+
251
277
  # memory_read would answer now for the names the item's latest read
@@ -33,7 +33,7 @@ module Samagotchi
33
33
  WorkingSetSteer::ADD => "added", WorkingSetSteer::UNADD => "unadded" }.freeze
34
34
  PIN_OPS = [WorkingSetSteer::PIN, WorkingSetSteer::UNPIN].freeze
35
35
 
36
- # @param engine [Engine] #session, #working_set_strategy, #prompt_memory_names,
36
+ # @param engine [Engine] #session, #working_set_strategy, #working_set_view, #prompt_memories,
37
37
  # #clone_messages, #replace_messages
38
38
  # @param save [#call] saves the session after a change
39
39
  def initialize(engine:, save:)
@@ -77,14 +77,17 @@ module Samagotchi
77
77
  [lines.join("\n"), changed, done.positive? ? :ok : :error]
78
78
  end
79
79
 
80
- # The set under the strategy the next turn runs, and the pending ops.
80
+ # The set as the model has it now (Engine#working_set_view: the running
81
+ # turn's as of its last request, else the session's under the next
82
+ # turn's strategy), and the pending ops (mid-turn the turn's copy holds
83
+ # the sent note, so none are).
81
84
  def listing
82
85
  session = @engine.session
83
- return Session::NONE_YET unless session
86
+ view = session && @engine.working_set_view
87
+ return Session::NONE_YET unless view
84
88
 
85
- messages = Array(session.messages)
86
- items = WorkingSet.build(messages, cwd: session.working_directory, strategy: @engine.working_set_strategy,
87
- pins: session.working_set_pins).items
89
+ messages = view.conversation
90
+ items = WorkingSet.build(messages, cwd: view.cwd, strategy: view.strategy, pins: session.working_set_pins).items
88
91
  return "working set: empty (the files, memories and URLs the turns read show here)\n#{USAGE}" if items.empty?
89
92
 
90
93
  rows = items.map { |item| [WorkingSetSteer.quote(name(item, session.working_directory)), words(item)] }
@@ -111,7 +114,7 @@ module Samagotchi
111
114
  when WorkingSetSteer::UNPIN then WorkingSetSteer.unpin(pins, target)
112
115
  when WorkingSetSteer::ADD
113
116
  WorkingSetSteer.add(messages, target, strategy: strategy, cwd: cwd, found: method(:missing),
114
- in_prompt: @engine.prompt_memory_names)
117
+ in_prompt: @engine.prompt_memories)
115
118
  else WorkingSetSteer.unadd(messages, target)
116
119
  end
117
120
  end
@@ -262,7 +262,7 @@ module Samagotchi
262
262
  # of it sent), a dropped one (undrop it), a prompt-only memory, and one
263
263
  # added already.
264
264
  # @param found [#call] target → nil when it exists, else a Refused reason
265
- # @param in_prompt [Array<String>] memory names the system prompt holds
265
+ # @param in_prompt [Array<Array(String, String, nil)>] memory names and scopes the system prompt holds
266
266
  # @return [Done]
267
267
  # @raise [Refused]
268
268
  def add(conversation, target, strategy:, cwd:, found: ->(_) {}, in_prompt: [])
@@ -373,14 +373,7 @@ module Samagotchi
373
373
  def prompt_memory?(target, names)
374
374
  return false unless target.kind == WorkingSet::MEMORY
375
375
 
376
- name = normalized_memory_name(target.key)
377
- Array(names).any? { |prompt_name| normalized_memory_name(prompt_name) == name }
378
- end
379
-
380
- def normalized_memory_name(raw)
381
- value = raw.to_s.strip
382
- scope, name = value.split("/", 2)
383
- Tools::VALID_SCOPES.include?(scope) ? name : value
376
+ Tools::MemoryRead.prompt_memory?(target.key, names)
384
377
  end
385
378
 
386
379
  # The note listing +ops+: a tail system message, escaped like a context
@@ -426,7 +419,7 @@ module Samagotchi
426
419
  tokens >= 1000 ? format("%.1fk tokens", tokens / 1000.0) : "#{tokens} tokens"
427
420
  end
428
421
 
429
- private_class_method :relative, :shared_with, :drop_of, :known?, :live?, :layers, :same?, :prompt_memory?, :normalized_memory_name,
422
+ private_class_method :relative, :shared_with, :drop_of, :known?, :live?, :layers, :same?, :prompt_memory?,
430
423
  :labels, :call_of
431
424
  end
432
425
  end
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.177.0
4
+ version: 0.178.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dmitry Dedov
@@ -169,6 +169,7 @@ files:
169
169
  - docs/internals/participants.md
170
170
  - docs/internals/prompt-caching.md
171
171
  - docs/internals/remote-sessions.md
172
+ - docs/internals/session-lifecycle.md
172
173
  - docs/internals/tool-output-limits.md
173
174
  - docs/internals/web-frontend.md
174
175
  - docs/internals/web-push.md
@@ -688,12 +689,17 @@ files:
688
689
  - lib/samagotchi/session_field.rb
689
690
  - lib/samagotchi/session_inbox.rb
690
691
  - lib/samagotchi/session_inbox_delivery.rb
692
+ - lib/samagotchi/session_lifecycle.rb
693
+ - lib/samagotchi/session_lifecycle/allowed.rb
694
+ - lib/samagotchi/session_lifecycle/canonical.rb
695
+ - lib/samagotchi/session_lifecycle/reading.rb
691
696
  - lib/samagotchi/session_manager.rb
692
697
  - lib/samagotchi/session_manager/delivery.rb
693
698
  - lib/samagotchi/session_manager/emptiness.rb
694
699
  - lib/samagotchi/session_manager/lifecycle.rb
695
700
  - lib/samagotchi/session_manager/listing.rb
696
701
  - lib/samagotchi/session_manager/removal.rb
702
+ - lib/samagotchi/session_manager/running_tasks.rb
697
703
  - lib/samagotchi/session_manager/spawn.rb
698
704
  - lib/samagotchi/session_manager/worker_command.rb
699
705
  - lib/samagotchi/session_metrics.rb
@@ -1046,6 +1052,7 @@ files:
1046
1052
  - lib/samagotchi/web/public/revise_stack.js
1047
1053
  - lib/samagotchi/web/public/revise_switch.js
1048
1054
  - lib/samagotchi/web/public/route.js
1055
+ - lib/samagotchi/web/public/running_tasks.js
1049
1056
  - lib/samagotchi/web/public/scope.js
1050
1057
  - lib/samagotchi/web/public/scroll.js
1051
1058
  - lib/samagotchi/web/public/send_turn.js
@@ -1141,6 +1148,7 @@ files:
1141
1148
  - lib/samagotchi/web/public/working_set_rail.js
1142
1149
  - lib/samagotchi/web/public/working_set_view.js
1143
1150
  - lib/samagotchi/web/public/ws_cards.js
1151
+ - lib/samagotchi/web/public/ws_item_sig.js
1144
1152
  - lib/samagotchi/web/public/ws_peek.js
1145
1153
  - lib/samagotchi/web/public/ws_preview.css
1146
1154
  - lib/samagotchi/web/public/ws_reader.js