samagotchi 0.191.0 → 0.192.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 (74) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +40 -1
  3. data/docs/architecture.md +5 -4
  4. data/docs/bundles.md +1 -1
  5. data/docs/cli.md +15 -7
  6. data/docs/configuration.md +6 -1
  7. data/docs/internals/inline-widgets.md +2 -1
  8. data/docs/internals/participants.md +1 -5
  9. data/docs/internals/remote-sessions.md +3 -0
  10. data/docs/internals/session-lifecycle.md +33 -19
  11. data/docs/internals/web-frontend.md +107 -9
  12. data/docs/scheduling.md +7 -1
  13. data/docs/sessions.md +2 -2
  14. data/docs/testing.md +1 -2
  15. data/docs/thin-clients.md +98 -12
  16. data/lib/samagotchi/bridge.rb +2 -3
  17. data/lib/samagotchi/bundles/mcp/manifest.yml +4 -2
  18. data/lib/samagotchi/bundles/mcp/plugin.rb +7 -398
  19. data/lib/samagotchi/bundles/mcp/server_config.rb +158 -0
  20. data/lib/samagotchi/bundles/mcp/sign_in.rb +261 -0
  21. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  22. data/lib/samagotchi/client_id.rb +2 -19
  23. data/lib/samagotchi/compat.rb +1 -7
  24. data/lib/samagotchi/config.rb +3 -0
  25. data/lib/samagotchi/delivery.rb +1 -5
  26. data/lib/samagotchi/schedule_command.rb +1 -0
  27. data/lib/samagotchi/schedules/prune_part.rb +32 -0
  28. data/lib/samagotchi/schedules.rb +14 -9
  29. data/lib/samagotchi/session.rb +7 -0
  30. data/lib/samagotchi/session_access/remote.rb +1 -1
  31. data/lib/samagotchi/session_continue.rb +8 -1
  32. data/lib/samagotchi/session_lifecycle.rb +4 -0
  33. data/lib/samagotchi/session_manager/delivery.rb +0 -6
  34. data/lib/samagotchi/session_manager/lifecycle.rb +30 -17
  35. data/lib/samagotchi/session_manager/listing.rb +2 -1
  36. data/lib/samagotchi/session_manager/removal.rb +7 -5
  37. data/lib/samagotchi/session_manager/spawn.rb +2 -3
  38. data/lib/samagotchi/session_manager.rb +4 -0
  39. data/lib/samagotchi/session_row.rb +2 -0
  40. data/lib/samagotchi/session_transition.rb +61 -15
  41. data/lib/samagotchi/tools/cancel_schedule.rb +10 -6
  42. data/lib/samagotchi/version.rb +1 -1
  43. data/lib/samagotchi/web/app.rb +3 -1
  44. data/lib/samagotchi/web/ask_create.rb +138 -0
  45. data/lib/samagotchi/web/ask_routes.rb +56 -9
  46. data/lib/samagotchi/web/last_ask.rb +78 -0
  47. data/lib/samagotchi/web/public/answer_refs.js +3 -9
  48. data/lib/samagotchi/web/public/answer_write.js +28 -0
  49. data/lib/samagotchi/web/public/app.js +72 -96
  50. data/lib/samagotchi/web/public/block_fix.js +30 -12
  51. data/lib/samagotchi/web/public/chains.js +3 -1
  52. data/lib/samagotchi/web/public/command_list.js +5 -3
  53. data/lib/samagotchi/web/public/composer.js +9 -6
  54. data/lib/samagotchi/web/public/composer_mount.js +18 -11
  55. data/lib/samagotchi/web/public/draft_keys.js +10 -0
  56. data/lib/samagotchi/web/public/drafts.js +278 -0
  57. data/lib/samagotchi/web/public/owner_claim.js +7 -12
  58. data/lib/samagotchi/web/public/prompt_history.js +6 -0
  59. data/lib/samagotchi/web/public/send_turn.js +51 -20
  60. data/lib/samagotchi/web/public/session_actions.js +80 -16
  61. data/lib/samagotchi/web/public/session_prefs.js +9 -3
  62. data/lib/samagotchi/web/public/session_view.js +7 -2
  63. data/lib/samagotchi/web/public/turn_events.js +0 -2
  64. data/lib/samagotchi/web/public/unqueue.js +22 -9
  65. data/lib/samagotchi/web/public/viewer_self.js +1 -6
  66. data/lib/samagotchi/web/public/views.js +12 -1
  67. data/lib/samagotchi/web/session_access_routes.rb +6 -3
  68. data/lib/samagotchi/web/session_control.rb +4 -2
  69. data/lib/samagotchi/web/session_create.rb +50 -33
  70. data/lib/samagotchi/web/session_hub.rb +52 -36
  71. data/lib/samagotchi/web/session_summary.rb +45 -7
  72. data/lib/samagotchi/web/start_dir.rb +6 -4
  73. data/lib/samagotchi/worker_presence.rb +22 -6
  74. metadata +8 -1
@@ -39,7 +39,7 @@ module Samagotchi
39
39
  # @param include_archived [Boolean] archived sessions too
40
40
  # @return [Array<SessionRow>] see SessionRow for the fields
41
41
  def session_rows(live: false, cwd: nil, limit: nil, include_tests: true, exclude: nil, state_dir: nil,
42
- project_root: nil, include_archived: false, sort: nil, order: nil)
42
+ project_root: nil, include_archived: false, sort: nil, order: nil, exclude_delegates: false)
43
43
  sd = state_dir || Session.default_state_dir
44
44
  SessionContinue.repair_interrupted(state_dir: sd)
45
45
  root = cwd && folder_path(cwd)
@@ -51,6 +51,7 @@ module Samagotchi
51
51
  rows = Session.list(state_dir: sd, sort: sort || "updated_at", order: order || "desc", project_root: project_root,
52
52
  include_archived: include_archived).lazy
53
53
  .reject { |s| (!include_tests && s.test_run) || s.id == exclude }
54
+ .reject { |s| exclude_delegates && (s.delegate? || s.scratch) }
54
55
  .select { |s| root.nil? || in_folder?(s.working_directory, root) }
55
56
  .filter_map do |s|
56
57
  dir = Session.session_dir(s.id, state_dir: sd)
@@ -46,9 +46,10 @@ module Samagotchi
46
46
 
47
47
  # A delete's refusal for a transition lock not taken in time
48
48
  # (SessionTransition::Busy, which names the holder): :continuing when
49
- # a continue holds it, else :transition_held; Busy's words either way.
49
+ # a continue holds it, else :transition_held; Busy's words either way,
50
+ # with "try again" (Busy#retry_message: a stop's words name no delete).
50
51
  def self.held(busy)
51
- new(busy.session_id, busy.kind == :continue ? :continuing : :transition_held, message: busy.message)
52
+ new(busy.session_id, busy.kind == :continue ? :continuing : :transition_held, message: busy.retry_message)
52
53
  end
53
54
 
54
55
  # This refusal, saying the op stopped +worker_id+'s worker (this
@@ -104,11 +105,12 @@ module Samagotchi
104
105
 
105
106
  # An archive's refusal for a transition lock not taken in time (its
106
107
  # own, or a worker's stop's: SessionTransition::Busy, which names the
107
- # holder and the session held): :transition_held, Busy's words;
108
- # +stopped_workers+ the workers it stopped before.
108
+ # holder and the session held): :transition_held, Busy's words with
109
+ # "try again" (Busy#retry_message); +stopped_workers+ the workers it
110
+ # stopped before.
109
111
  def self.held(busy, stopped_workers: [])
110
112
  new(busy.session_id, :transition_held, busy_id: busy.session_id, stopped_workers: stopped_workers,
111
- message: busy.message)
113
+ message: busy.retry_message)
112
114
  end
113
115
 
114
116
  def worker_stopped = !@stopped_worker.nil?
@@ -69,9 +69,8 @@ module Samagotchi
69
69
  setup: SessionSetup.new, continues: nil, note: nil, note_source: "chi", before_spawn: nil,
70
70
  review: nil, verify_fresh: nil, scratch: false, session_id: nil, driver: :creator)
71
71
  sd = state_dir || Session.default_state_dir
72
- if session_id && (!Session.valid_id?(session_id) || Session.exist?(session_id, state_dir: sd))
73
- raise ArgumentError, "invalid or existing session id #{session_id.inspect}"
74
- end
72
+ raise ArgumentError, "invalid session id #{session_id.inspect}" if session_id && !Session.valid_id?(session_id)
73
+ raise IdTaken, "existing session id #{session_id.inspect}" if session_id && Session.exist?(session_id, state_dir: sd)
75
74
 
76
75
  # The resolved ref is stored (a resumed session keeps its model when an
77
76
  # alias is retargeted), with the name as typed beside it. A wrong host
@@ -122,6 +122,10 @@ module Samagotchi
122
122
  end
123
123
  end
124
124
 
125
+ # spawn_session's session_id: is a session already (a retried create
126
+ # whose id its request_id names: Web::AskCreate goes on with that one).
127
+ class IdTaken < ArgumentError; end
128
+
125
129
  # A `chi scratch` session: its terminal's alone (Session::SCRATCH_REFUSED).
126
130
  # An OwnedByTUI, so every caller that refuses a terminal's session
127
131
  # (chi send, chi web's 409 owned_by_tui) refuses it the same way.
@@ -22,6 +22,8 @@ module Samagotchi
22
22
  # The liveness rule: +live+ is WorkerLink's worker_owned? (a worker holds
23
23
  # the lock, its Bridge up or on its way); +busy+ and +waiting+ need it,
24
24
  # +status+ is Session#displayed_status (a dead worker's "running" is idle).
25
+ # The session hub shows neither this live nor its question: it reads
26
+ # SessionSummary.shown (the lifecycle state).
25
27
  SessionRow = Data.define(:id, :desc, :preview, :title, :cwd, :project, :updated_at, :status, :saved_status, :live,
26
28
  :busy, :owner, :recap, :auto_title, :ctx_pct, :parent_id, :continues, :delegate, :archived,
27
29
  :scratch, :test_run, :stopped_by, :waiting, :waiting_id, :relayed_to)
@@ -42,19 +42,30 @@ module Samagotchi
42
42
  # change" (a shared holder, an older chi's, a kind this chi doesn't
43
43
  # name). A nil +session_id+ says "this session" (a peer's line,
44
44
  # which carries no id).
45
+ #
46
+ # #retry_message is those words with "; try again in a moment". A
47
+ # stop's (+taker+ :stop) that met a transition (#transition?: one that
48
+ # won't let go soon) says what to do instead: "session X is being
49
+ # deleted", "… being archived", "… being continued as Y: stop that one".
50
+ # Every other taker's #message is #retry_message.
45
51
  class Busy < StandardError
46
52
  WORDS = { continue: "being continued", delete: "being deleted", stop: "being stopped", archive: "being archived",
47
53
  nil => "busy with another change" }.freeze
54
+ # The holders a stop doesn't wait for (#transition?): a delete or an
55
+ # archive, a continue once it names its new link.
56
+ TRANSITIONS = %i[delete archive continue].freeze
48
57
 
49
58
  # +kind+ the holder's (nil: not told), +successor_id+ the new link a
50
- # continue holding it names.
51
- attr_reader :session_id, :kind, :successor_id
59
+ # continue holding it names, +taker+ the kind of the hold that met it
60
+ # (nil: an arrival, or not told).
61
+ attr_reader :session_id, :kind, :successor_id, :taker
52
62
 
53
- def initialize(session_id, kind: nil, successor_id: nil)
63
+ def initialize(session_id, kind: nil, successor_id: nil, taker: nil)
54
64
  @session_id = session_id
55
65
  @kind = kind
56
66
  @successor_id = successor_id
57
- super("#{words}; try again in a moment")
67
+ @taker = taker
68
+ super(taker == :stop && transition? ? stop_words : retry_message)
58
69
  end
59
70
 
60
71
  # The refusal of an arrival or a taker that met +session_id+'s lock
@@ -63,17 +74,29 @@ module Samagotchi
63
74
  # or an archive is said as such whatever else is on disk (a crashed
64
75
  # continue's intent); else a continue in flight
65
76
  # (ContinueIntent.in_flight: an older chi's records no kind) names
66
- # its new link.
77
+ # its new link. +taker+ is the kind of the hold that met it.
67
78
  # @return [Busy]
68
- def self.held(session_id, state_dir:)
79
+ def self.held(session_id, state_dir:, taker: nil)
69
80
  kind = SessionTransition.holder(session_id, state_dir: state_dir)
70
- return new(session_id, kind: kind) if SessionTransition.other_than_continue?(kind)
81
+ return new(session_id, kind: kind, taker: taker) if SessionTransition.other_than_continue?(kind)
71
82
 
72
83
  require_relative "continue_intent"
73
84
  successor = session_id && ContinueIntent.in_flight(session_id, state_dir: state_dir)
74
- new(session_id, kind: successor ? :continue : kind, successor_id: successor)
85
+ new(session_id, kind: successor ? :continue : kind, successor_id: successor, taker: taker)
75
86
  end
76
87
 
88
+ # Whether the holder is a transition that won't let go soon: a delete,
89
+ # an archive, a continue that names its new link. A stop, a repair, a
90
+ # holder that names nothing (an older chi's, a continue before its
91
+ # intent names the new link, the new link's own hold) and every
92
+ # shared hold (a send) are short, or can't be told: waited out.
93
+ def transition?
94
+ TRANSITIONS.include?(@kind) && (@kind != :continue || !@successor_id.nil?)
95
+ end
96
+
97
+ # The holder's words, "; try again in a moment".
98
+ def retry_message = "#{words}; try again in a moment"
99
+
77
100
  private
78
101
 
79
102
  def words
@@ -85,6 +108,10 @@ module Samagotchi
85
108
  subject = @session_id ? "session #{@session_id.to_s[0, 8]}" : "this session"
86
109
  "#{subject} is #{WORDS.fetch(@kind, WORDS[nil])}"
87
110
  end
111
+
112
+ # A stop's words for a transition: a continue's new link is the one
113
+ # to stop; a delete or an archive leaves nothing to stop.
114
+ def stop_words = @successor_id ? "#{words}: stop that one" : words
88
115
  end
89
116
 
90
117
  module_function
@@ -92,15 +119,25 @@ module Samagotchi
92
119
  # The block under an exclusive hold of every id's lock, taken in sorted
93
120
  # order, each folder created when missing. Ids this thread already holds
94
121
  # are passed through. +deadline+ nil blocks until each lock is free;
95
- # seconds try each until then.
122
+ # seconds try each until then. With +refuse_transitions+ (a stop's:
123
+ # +deadline+ required) each failed try reads the holder again, and one
124
+ # that is a transition (Busy#transition?: a delete, an archive, a
125
+ # continue naming its new link) is refused at once rather than waited
126
+ # for; a short hold (a send's shared one) or one that names nothing is
127
+ # still waited out to the deadline.
96
128
  # @yieldparam token [Token]
97
129
  # @return the block's value
98
- # @raise [Busy] an id not taken in time (the ids taken before it are let go)
99
- # @raise [ArgumentError] an id that isn't a session id
100
- def exclusive(ids, kind:, state_dir:, deadline: nil)
130
+ # @raise [Busy] an id not taken in time, or held by a transition with
131
+ # +refuse_transitions+ (the ids taken before it are let go); its
132
+ # +taker+ is +kind+
133
+ # @raise [ArgumentError] an id that isn't a session id, or
134
+ # +refuse_transitions+ with no +deadline+ (a blocking flock reads no
135
+ # holder)
136
+ def exclusive(ids, kind:, state_dir:, deadline: nil, refuse_transitions: false)
101
137
  ids = Array(ids).uniq.sort
102
138
  bad = ids.reject { |id| Session.valid_id?(id) }
103
139
  raise ArgumentError, "not a session id: #{bad.first.inspect}" unless bad.empty?
140
+ raise ArgumentError, "refuse_transitions needs a deadline" if refuse_transitions && deadline.nil?
104
141
 
105
142
  ends_at = monotonic + deadline if deadline
106
143
  taken = []
@@ -111,7 +148,13 @@ module Samagotchi
111
148
  FileUtils.mkdir_p(File.dirname(path))
112
149
  file = File.open(path, File::RDWR | File::CREAT, 0o600) # rubocop:disable Style/FileOpen -- held past this loop, closed in the ensure
113
150
  taken << [path, file]
114
- lock_until(file, ends_at) or raise Busy.held(id, state_dir: state_dir)
151
+ refuse = if refuse_transitions
152
+ lambda {
153
+ busy = Busy.held(id, state_dir: state_dir, taker: kind)
154
+ raise busy if busy.transition?
155
+ }
156
+ end
157
+ lock_until(file, ends_at, refuse: refuse) or raise Busy.held(id, state_dir: state_dir, taker: kind)
115
158
  holds[path] = true
116
159
  mark(file, kind)
117
160
  end
@@ -293,8 +336,9 @@ module Samagotchi
293
336
  end
294
337
 
295
338
  # Lock +file+ exclusively: blocking when +ends_at+ is nil, else tried
296
- # until that monotonic time. Whether it was taken.
297
- def lock_until(file, ends_at)
339
+ # until that monotonic time, +refuse+ (when given) called after each
340
+ # failed try (it raises to give up at once). Whether it was taken.
341
+ def lock_until(file, ends_at, refuse: nil)
298
342
  unless ends_at
299
343
  file.flock(File::LOCK_EX)
300
344
  return true
@@ -302,6 +346,8 @@ module Samagotchi
302
346
 
303
347
  loop do
304
348
  return true if file.flock(File::LOCK_EX | File::LOCK_NB)
349
+
350
+ refuse&.call
305
351
  return false if monotonic >= ends_at
306
352
 
307
353
  sleep RETRY
@@ -31,9 +31,8 @@ module Samagotchi
31
31
 
32
32
  # nil: gone since the lookup (another cancel in between).
33
33
  if want_all || peers&.session_id.nil?
34
- return "No schedule named #{name}." unless schedules.cancel(name)
35
-
36
- return "Cancelled #{entry.id} (#{entry.title || entry.recurrence_words})."
34
+ cancelled = schedules.cancel(name)
35
+ return cancelled ? cancelled_answer(entry, cancelled) : "No schedule named #{name}."
37
36
  end
38
37
 
39
38
  unless schedules.chain_of(peers.session_id).any? { |id| id == entry.anchor || id == entry.head }
@@ -41,13 +40,18 @@ module Samagotchi
41
40
  "chi schedule cancel #{entry.id} cancels it, or say all: true if you meant it."
42
41
  end
43
42
 
44
- return "No schedule named #{name}." unless schedules.cancel(name)
45
-
46
- "Cancelled #{entry.id} (#{entry.title || entry.recurrence_words})."
43
+ cancelled = schedules.cancel(name)
44
+ cancelled ? cancelled_answer(entry, cancelled) : "No schedule named #{name}."
47
45
  rescue StandardError => e
48
46
  "Error: #{e.message}"
49
47
  end
50
48
 
49
+ # The answer for a cancelled +entry+, with the Schedules::Cancelled line
50
+ # naming the chain's newest link when the cancel ended a pruned anchor's bridge.
51
+ def self.cancelled_answer(entry, cancelled)
52
+ ["Cancelled #{entry.id} (#{entry.title || entry.recurrence_words}).", cancelled.warning].compact.join("\n")
53
+ end
54
+
51
55
  # @return [String] the answer for +name+ when no readable entry has it
52
56
  def self.cancel_unreadable(schedules, name, want_all, peers)
53
57
  raw = schedules.unreadable_record(name)
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.191.0"
4
+ VERSION = "0.192.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -79,6 +79,7 @@ require_relative "participant_show"
79
79
  require_relative "message_display"
80
80
  require_relative "session_show"
81
81
  require_relative "session_create"
82
+ require_relative "ask_create"
82
83
  require_relative "session_control"
83
84
  require_relative "verify_fresh_routes"
84
85
  require_relative "block_fix_routes"
@@ -121,6 +122,7 @@ module Samagotchi
121
122
  include MessageDisplay
122
123
  include SessionShow
123
124
  include SessionCreate
125
+ include AskCreate
124
126
  include SessionControl
125
127
  include VerifyFreshRoutes
126
128
  include BlockFixRoutes
@@ -1126,7 +1128,7 @@ module Samagotchi
1126
1128
  # delegates: chi --remote sessions delete --dry-run asks for this first.
1127
1129
  DELETE_PLAN_FEATURE = "delete_plan_all"
1128
1130
  INFO_FEATURES = ["dir", "newest_workers", SessionAccessRoutes::FEATURE, SessionAccessRoutes::ATTACH_FEATURE,
1129
- BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE, ASK_FEATURE, McpRoute::FEATURE, Delivery::AGENT_FEATURE, ReplyFor::FEATURE, PeerMailbox::FEATURE].freeze
1131
+ BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE, ASK_FEATURE, ASK_LAST_FEATURE, AskCreate::FEATURE, McpRoute::FEATURE, Delivery::AGENT_FEATURE, ReplyFor::FEATURE, PeerMailbox::FEATURE].freeze
1130
1132
 
1131
1133
  # The models a new session can start on, spelled as chi spells them
1132
1134
  # elsewhere: bare for the default host (what default.model holds), and
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../client_id"
4
+ require_relative "../config"
5
+ require_relative "../guardrails/parent_policy"
6
+ require_relative "../model_profile"
7
+ require_relative "../session"
8
+ require_relative "../session_inbox"
9
+ require_relative "../session_manager"
10
+ require_relative "last_ask"
11
+ require_relative "start_dir"
12
+
13
+ module Samagotchi
14
+ module Web
15
+ # POST /api/sessions answering its first turn (docs/thin-clients.md "A
16
+ # new session in one call"): a create with any of reply_for, timeout or
17
+ # request_id (ASK_FIELDS) spawns the session idle, its prompt as the
18
+ # preview, then runs the same SessionAccess::Ask an /ask runs
19
+ # (AskRoutes#run_ask), all within one ASK_MAX_SECONDS deadline. Included
20
+ # in App beside SessionCreate (which hands such a body here) and
21
+ # AskRoutes, whose readers and response builders it uses.
22
+ module AskCreate
23
+ # The body fields that make a create answer its first turn.
24
+ ASK_FIELDS = %w[reply_for timeout request_id].freeze
25
+ # GET /api/info's feature: this chi web's create answers its first turn.
26
+ FEATURE = "ask_create"
27
+ INLINE_ONLY = "an answered create starts a new session with a prompt: leave out idle and continues"
28
+
29
+ # One lock per derived session id, held over the check, the spawn and
30
+ # the Ask: two same-request_id creates at once make one session and
31
+ # one turn. chi web is the only creator of these ids.
32
+ LOCKS = {}
33
+ LOCKS_GUARD = Mutex.new
34
+
35
+ def self.inline?(body) = ASK_FIELDS.any? { |key| body.key?(key) }
36
+
37
+ # The block under +id+'s lock (none for nil), the entry dropped once
38
+ # nobody holds or waits for it.
39
+ def self.locked(id, &)
40
+ return yield if id.nil?
41
+
42
+ entry = LOCKS_GUARD.synchronize { (LOCKS[id] ||= [Mutex.new, 0]).tap { |e| e[1] += 1 } }
43
+ begin
44
+ entry[0].synchronize(&)
45
+ ensure
46
+ LOCKS_GUARD.synchronize { LOCKS.delete(id) if (entry[1] -= 1).zero? }
47
+ end
48
+ end
49
+
50
+ private
51
+
52
+ # The inline create: the ask's fields read first (a bad timeout,
53
+ # request_id or reply_for, a UI-only command, an oversize prompt spawn
54
+ # nothing), then the folder (the body's dir, else web.ask_dir, else
55
+ # chi web's start folder) and every check a create makes, then the
56
+ # idle spawn (with a request_id, at the id it names: a retry finds it
57
+ # and spawns nothing) and the Ask. 201 with the ask's answer
58
+ # (AskRoutes#ask_response's fields; session_id, created, model_warning,
59
+ # parent_answers_warning); a refusal after the spawn keeps its code
60
+ # and carries session_id and created. The owner's own create is their
61
+ # `last` (LastAsk), refused or not.
62
+ def handle_ask_create(body, deadline)
63
+ if body["idle"] == true || body.key?("continues")
64
+ return error_response(400, "invalid_ask", INLINE_ONLY)
65
+ end
66
+
67
+ prompt, client_id, options, reply_for, error = ask_fields(body, id: nil)
68
+ return error if error
69
+
70
+ dir, error = ask_create_dir(body)
71
+ return error if error
72
+
73
+ folder, parent_answers, error = create_fields(body, prompt, dir: dir)
74
+ return error if error
75
+
76
+ request_id = options[:request_id]
77
+ session_id = request_id && SessionInbox.enqueued_id_for("create:#{request_id}")
78
+ AskCreate.locked(session_id) do
79
+ session, error = ask_create_spawn(body, prompt, folder, session_id)
80
+ return error if error
81
+
82
+ sid = session&.id || session_id
83
+ @hub&.touch(sid)
84
+ extra = { session_id: sid, created: !session.nil?, model_warning: session&.model_warning,
85
+ parent_answers_warning: Guardrails::ParentPolicy.capped_note(parent_answers) }
86
+ response = ask_create_run(sid, prompt, client_id, options, reply_for, deadline, body, extra)
87
+ LastAsk.record(sid, state_dir: default_state_dir) unless ClientId.parent_line?(client_id)
88
+ response
89
+ end
90
+ end
91
+
92
+ # The inline create's folder: [dir, nil] or [nil, a 400 invalid_dir].
93
+ # web.ask_dir (read now, StartDir's rules, from home) when the body
94
+ # names none; unset, chi web's start folder.
95
+ def ask_create_dir(body)
96
+ dir, error = scope_dir(body["dir"])
97
+ return [nil, error] if error
98
+ return [dir, nil] if dir
99
+
100
+ configured = Config.get("web.ask_dir")
101
+ return [start_dir, nil] if configured.to_s.strip.empty?
102
+
103
+ [StartDir.resolve(configured, from: :ask_config), nil]
104
+ rescue StartDir::Invalid => e
105
+ [nil, error_response(400, "invalid_dir", e.message)]
106
+ end
107
+
108
+ # The idle spawn, prompt as its preview: [session, nil]; [nil, nil]
109
+ # when +session_id+ (a request_id's) is a session already (a retry:
110
+ # nothing spawns); [nil, a 400 invalid_model].
111
+ def ask_create_spawn(body, prompt, folder, session_id)
112
+ return [nil, nil] if session_id && Session.exist?(session_id, state_dir: default_state_dir)
113
+
114
+ ids = session_id ? { session_id: session_id } : {}
115
+ session = @manager.spawn_session(prompt: nil, preview: prompt.strip, client_id: body["client_id"] || ClientId::WEB_CREATE,
116
+ state_dir: @state_dir, **folder, **ids)
117
+ [session, nil]
118
+ rescue ModelProfile::MissingModel => e
119
+ [nil, error_response(400, "invalid_model", e.message)]
120
+ rescue SessionManager::IdTaken
121
+ [nil, nil]
122
+ end
123
+
124
+ # The Ask on the new (or retried) session, its answer a 201 with
125
+ # +extra+ (a refusal keeps its code). Not a :session route: a session
126
+ # deleted meanwhile is 404 here, and a one-turn chi run's 409 too.
127
+ def ask_create_run(sid, prompt, client_id, options, reply_for, deadline, body, extra)
128
+ outcome = run_ask(sid, prompt: prompt, client_id: client_id, options: options, deadline: deadline, body: body)
129
+ response = ask_response(sid, outcome, request_id: options[:request_id], reply_for: reply_for)
130
+ with_fields(response, status: (201 if response.first == 200), **extra)
131
+ rescue SessionManager::OwnedByTUI => e
132
+ with_fields(owned_by_tui(e), **extra)
133
+ rescue ArgumentError => e
134
+ with_fields(error_response(404, "not_found", e.message), **extra)
135
+ end
136
+ end
137
+ end
138
+ end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "delegate"
4
+ require "json"
4
5
  require_relative "../bridge_client"
5
6
  require_relative "../agent_caller"
6
7
  require_relative "../client_id"
@@ -15,6 +16,7 @@ require_relative "../session_access/exchange"
15
16
  require_relative "../session_access/exchange/token"
16
17
  require_relative "../reply_for"
17
18
  require_relative "../turn_anchors"
19
+ require_relative "last_ask"
18
20
  require_relative "request_body"
19
21
 
20
22
  module Samagotchi
@@ -49,6 +51,8 @@ module Samagotchi
49
51
  # GET /api/info's feature: this chi web has the ask route, wait
50
52
  # tokens, the answer's wait and the create's token.
51
53
  ASK_FEATURE = "ask"
54
+ # GET /api/info's feature: POST /api/sessions/last/ask (LastAsk).
55
+ ASK_LAST_FEATURE = "ask_last"
52
56
  # A line a worker may run as a session command (#ask_request_id): a
53
57
  # / name (Registry::UNKNOWN_COMMAND_WORD's shape, which every
54
58
  # built-in a worker runs and a bundle's COMMAND_NAME fits) followed by
@@ -105,30 +109,73 @@ module Samagotchi
105
109
  # waits, the Bridge wait and the slice all draw on it.
106
110
  deadline = ask_clock + ASK_MAX_SECONDS
107
111
  body = body_hash(req) or return error_response(400, "invalid_json", "invalid JSON body")
108
- prompt, client_id, options, error = ask_request(id, body)
109
- return error if error
112
+ # `last` (LastAsk): the session the owner last asked, resolved here
113
+ # (the route's gates saw the address: a participant's is a 404).
114
+ if id == LastAsk::ADDRESS
115
+ id = LastAsk.target(state_dir: default_state_dir) or return error_response(404, "not_found", LastAsk::NOT_FOUND)
116
+ end
110
117
 
111
- reply_for, error = ask_reply_for(body)
118
+ prompt, client_id, options, reply_for, error = ask_fields(body, id: id)
112
119
  return error if error
113
120
 
114
- options[:anchors] = TurnAnchors.new(reply_for: reply_for) if reply_for && !runs_as_command?(prompt, client_id)
115
-
116
121
  gated = ask_gate(id, prompt, client_id)
117
122
  return gated if gated
118
123
 
124
+ outcome = run_ask(id, prompt: prompt, client_id: client_id, options: options, deadline: deadline, body: body)
125
+ record_last(outcome, client_id)
126
+ ask_response(id, outcome, request_id: options[:request_id], reply_for: reply_for)
127
+ rescue SessionManager::OwnedByTUI => e
128
+ owned_by_tui(e)
129
+ end
130
+
131
+ # An ask's body read whole (#ask_request, #ask_reply_for, the turn's
132
+ # anchor): [prompt, client_id, options, reply_for, nil] or [nil, nil,
133
+ # nil, nil, a 400 response]. +id+: the session asked, which a
134
+ # UI-only command's refusal names (nil: none yet, "ID").
135
+ def ask_fields(body, id:)
136
+ prompt, client_id, options, error = ask_request(id, body)
137
+ return [nil, nil, nil, nil, error] if error
138
+
139
+ reply_for, error = ask_reply_for(body)
140
+ return [nil, nil, nil, nil, error] if error
141
+
142
+ options[:anchors] = TurnAnchors.new(reply_for: reply_for) if reply_for && !runs_as_command?(prompt, client_id)
143
+ [prompt, client_id, options, reply_for, nil]
144
+ end
145
+
146
+ # The ask itself (SessionAccess::Ask through chi web's manager and
147
+ # Bridge, all within +deadline+), its history line recorded unless it
148
+ # was refused or rebound to a turn already known.
149
+ # @return [SessionAccess::Ask::Reply, Ran, Refused] the outcome
150
+ def run_ask(id, prompt:, client_id:, options:, deadline:, body:)
119
151
  bridge = ->(sid) { ask_bridge(sid, deadline) }
120
152
  access = AskAccess.new(session_access, manager: @manager, bridge: bridge, poll_interval: @wait_poll_interval)
121
153
  stopping = -> { !@server_running.call }
122
154
  exchange = SessionAccess::Exchange.new(access, continuing_wait: [SessionAccess::Exchange::CONTINUING_WAIT,
123
155
  ASK_MAX_SECONDS].min, cancelled: stopping)
124
156
  outcome = SessionAccess::Ask.new(access, exchange: exchange)
125
- .call(id, prompt: prompt, client_id: client_id, cap: deadline - ask_clock,
157
+ .call(id, prompt: prompt, client_id: client_id, cap: (deadline - ask_clock).clamp(0.0..),
126
158
  cancelled: stopping, **options)
127
159
  rebound = outcome.is_a?(SessionAccess::Ask::Reply) && outcome.rebound
128
160
  record_history(body, prompt) unless outcome.is_a?(SessionAccess::Ask::Refused) || rebound
129
- ask_response(id, outcome, request_id: options[:request_id], reply_for: reply_for)
130
- rescue SessionManager::OwnedByTUI => e
131
- owned_by_tui(e)
161
+ outcome
162
+ end
163
+
164
+ # The session an answered ask ran in as the owner's `last`
165
+ # (LastAsk.record): not a refused ask's, nor a line a parent agent
166
+ # or chi send sent (ClientId.parent_line?).
167
+ def record_last(outcome, client_id)
168
+ return if outcome.is_a?(SessionAccess::Ask::Refused) || ClientId.parent_line?(client_id)
169
+
170
+ LastAsk.record(outcome.session_id, state_dir: default_state_dir)
171
+ end
172
+
173
+ # A json_response triple re-rendered with +extra+ keys added (its own
174
+ # keys win: an ask's session_id is where it ran) and +status+ in place
175
+ # of its own when given.
176
+ def with_fields(response, status: nil, **extra)
177
+ code, _headers, chunks = response
178
+ json_response(status || code, JSON.parse(chunks.join).merge(extra.transform_keys(&:to_s)) { |_key, own, _new| own })
132
179
  end
133
180
 
134
181
  # The ask's body read: [prompt, client_id, {queue:, timeout:,
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "fileutils"
5
+ require "time"
6
+ require_relative "../archive_store"
7
+ require_relative "../atomic_file"
8
+ require_relative "../log"
9
+ require_relative "../session"
10
+ require_relative "../session_inbox_delivery"
11
+
12
+ module Samagotchi
13
+ module Web
14
+ # A thin client's `last` (POST /api/sessions/last/ask,
15
+ # docs/thin-clients.md "Your last session"): the session that most
16
+ # recently got an owner's thin-client ask (an /ask, or a create that
17
+ # answers its first turn), kept as one id in FILE beside the sessions
18
+ # folder (as Schedules keeps its file), and the fallback when it is gone.
19
+ # Only AskRoutes records it, and only for the owner's own lines (an
20
+ # agent's or chi send's leave it): it is the owner's conversation.
21
+ module LastAsk
22
+ module_function
23
+
24
+ # The address a thin client asks in place of an id.
25
+ ADDRESS = "last"
26
+ FILE = "last_ask.json"
27
+ NOT_FOUND = "no session to ask as last: start one with POST /api/sessions"
28
+
29
+ def path(state_dir:) = File.join(File.dirname(File.expand_path(state_dir)), FILE)
30
+
31
+ # +session_id+ as the last one asked. Never raises: a write that
32
+ # can't happen is logged, and the ask still answers.
33
+ def record(session_id, state_dir:, at: Time.now)
34
+ file = path(state_dir: state_dir)
35
+ FileUtils.mkdir_p(File.dirname(file))
36
+ AtomicFile.write(file, JSON.generate({ "session_id" => session_id, "at" => at.utc.iso8601(3) }), perm: 0o600)
37
+ rescue StandardError => e
38
+ Log.warn(:web, "last_ask_write_failed", session_id: session_id, msg: "#{e.class}: #{e.message}")
39
+ end
40
+
41
+ # @return [String, nil] the recorded id; nil when none, or the file
42
+ # is unreadable or holds no session id
43
+ def recorded(state_dir:)
44
+ data = JSON.parse(File.read(path(state_dir: state_dir)))
45
+ id = data["session_id"] if data.is_a?(Hash)
46
+ Session.valid_id?(id) ? id : nil
47
+ rescue SystemCallError, IOError, JSON::ParserError
48
+ nil
49
+ end
50
+
51
+ # The session `last` names: the recorded one while its file is there
52
+ # and it is not archived with nothing continuing it (a continued one
53
+ # keeps its id: the ask follows the chain to its newest link, a
54
+ # continue in flight included); else #recent.
55
+ # @param head [#call] id → SessionInbox::Resolved (a send's chain walk)
56
+ # @return [String, nil] nil: no session to ask
57
+ def target(state_dir:, head: ->(id) { SessionInbox::Head.resolve(:send, id, state_dir: state_dir) })
58
+ id = recorded(state_dir: state_dir)
59
+ return recent(state_dir: state_dir) unless id && Session.exist?(id, state_dir: state_dir)
60
+ return id if head.call(id).id != id
61
+ return id unless ArchiveStore.archived?(Session.session_dir(id, state_dir: state_dir))
62
+
63
+ recent(state_dir: state_dir)
64
+ rescue ArgumentError # degrade-ok: deleted while resolving: the fallback
65
+ recent(state_dir: state_dir)
66
+ end
67
+
68
+ # The newest of the owner's own sessions (Session.list: archived left
69
+ # out, updated_at desc): not a chi scratch one, a delegate, one an
70
+ # agent drives, or a test run.
71
+ # @return [String, nil]
72
+ def recent(state_dir:)
73
+ Session.list(state_dir: state_dir)
74
+ .find { |s| !s.scratch && !s.delegate? && s.driver.nil? && !s.test_run }&.id
75
+ end
76
+ end
77
+ end
78
+ end
@@ -18,7 +18,8 @@
18
18
  // The match and label are a plugin's text: they only ever go through
19
19
  // textContent, setAttribute and bindRef, never markup or a RegExp.
20
20
 
21
- import { COPY_SOURCE_ATTR, copySource, showsAnswer } from "./copy.js";
21
+ import { showsAnswer } from "./copy.js";
22
+ import { writeAnswer } from "./answer_write.js";
22
23
  import { bindRef, boundRef, httpUrl, refKindOk } from "./refs.js";
23
24
 
24
25
  // bubble → {refs, paired}. A WeakMap: a dropped bubble takes its refs with
@@ -64,14 +65,7 @@ export function applyFinalAnswer(messages, bubbles, normalize) {
64
65
  );
65
66
  const bubble = message && [...bubbles].reverse().find((item) => showsAnswer(item, message, normalize));
66
67
  if (!bubble) return null;
67
- if (typeof message.html === "string") {
68
- bubble.classList.add("markdown");
69
- bubble.setAttribute(COPY_SOURCE_ATTR, copySource(message));
70
- // A hook's display in the answer's place (answer_fold.js's label).
71
- bubble.toggleAttribute("data-answer-display", typeof message.display === "string");
72
- // The server's rendered markdown, sanitized there (Web::MarkdownRenderer#sanitize): set as it is, not templated.
73
- bubble.innerHTML = message.html;
74
- }
68
+ writeAnswer(bubble, message);
75
69
  setAnswerRefs(bubble, message.display_refs);
76
70
  return bubble;
77
71
  }