samagotchi 0.181.0 → 0.183.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 (200) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +93 -1
  3. data/bin/chi +4 -1
  4. data/docs/architecture.md +17 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +58 -10
  8. data/docs/configuration.md +3 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +172 -3
  11. data/docs/internals/bridge.md +23 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +29 -8
  14. data/docs/internals/inline-widgets.md +3 -1
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +38 -7
  17. data/docs/internals/web-frontend.md +116 -26
  18. data/docs/internals/working-set.md +1 -1
  19. data/docs/mcp-server.md +80 -0
  20. data/docs/plugins.md +308 -21
  21. data/docs/sessions.md +7 -4
  22. data/docs/sub-agent.md +9 -0
  23. data/docs/testing.md +3 -1
  24. data/docs/thin-clients.md +146 -0
  25. data/lib/samagotchi/answer_display.rb +3 -2
  26. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  27. data/lib/samagotchi/block_fix.rb +220 -0
  28. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  29. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  30. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  31. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  32. data/lib/samagotchi/bridge.rb +69 -69
  33. data/lib/samagotchi/bridge_client.rb +9 -0
  34. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  35. data/lib/samagotchi/bundle_command/check.rb +36 -19
  36. data/lib/samagotchi/bundle_command.rb +50 -21
  37. data/lib/samagotchi/bundle_manifest.rb +101 -4
  38. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  40. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  41. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  42. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  43. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  44. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  45. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  46. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  47. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  48. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  49. data/lib/samagotchi/command_intake.rb +7 -0
  50. data/lib/samagotchi/commands/registry.rb +8 -3
  51. data/lib/samagotchi/config.rb +3 -0
  52. data/lib/samagotchi/continue_intent.rb +8 -0
  53. data/lib/samagotchi/continue_offer.rb +24 -15
  54. data/lib/samagotchi/engine/block_fix.rb +332 -0
  55. data/lib/samagotchi/engine/cards.rb +14 -5
  56. data/lib/samagotchi/engine/events.rb +10 -15
  57. data/lib/samagotchi/engine/models.rb +1 -1
  58. data/lib/samagotchi/engine/plugins.rb +3 -0
  59. data/lib/samagotchi/engine/recap.rb +1 -1
  60. data/lib/samagotchi/engine/side_requests.rb +8 -6
  61. data/lib/samagotchi/engine/sign_in.rb +142 -0
  62. data/lib/samagotchi/engine/turn_end.rb +3 -3
  63. data/lib/samagotchi/engine.rb +47 -27
  64. data/lib/samagotchi/engine_snapshots.rb +1 -1
  65. data/lib/samagotchi/events.rb +1 -0
  66. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  67. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  68. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  69. data/lib/samagotchi/hold_stop.rb +4 -4
  70. data/lib/samagotchi/idle_client.rb +10 -6
  71. data/lib/samagotchi/idle_recap.rb +19 -11
  72. data/lib/samagotchi/idle_reminders.rb +7 -5
  73. data/lib/samagotchi/idle_scheduler.rb +7 -10
  74. data/lib/samagotchi/inline_widgets.rb +12 -0
  75. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  76. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  77. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  78. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  79. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  80. data/lib/samagotchi/kernel_loop.rb +7 -5
  81. data/lib/samagotchi/llm/chat_loop.rb +2 -0
  82. data/lib/samagotchi/llm/http.rb +96 -5
  83. data/lib/samagotchi/markdown_parser.rb +28 -0
  84. data/lib/samagotchi/mcp_command.rb +110 -0
  85. data/lib/samagotchi/mcp_server/http.rb +112 -0
  86. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  87. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  88. data/lib/samagotchi/mcp_server/text.rb +155 -0
  89. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  90. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  91. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  92. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  93. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  94. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  95. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  96. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  97. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  98. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  99. data/lib/samagotchi/plugin/api.rb +6 -1
  100. data/lib/samagotchi/plugin/card.rb +36 -11
  101. data/lib/samagotchi/plugin/context.rb +63 -6
  102. data/lib/samagotchi/plugin/http.rb +40 -15
  103. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  104. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  105. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  106. data/lib/samagotchi/plugin/loader.rb +18 -11
  107. data/lib/samagotchi/plugin/secrets.rb +266 -0
  108. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  109. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  110. data/lib/samagotchi/queued_command.rb +28 -4
  111. data/lib/samagotchi/recap_setup.rb +13 -4
  112. data/lib/samagotchi/ref.rb +3 -2
  113. data/lib/samagotchi/relay_verifier.rb +8 -7
  114. data/lib/samagotchi/relay_watcher.rb +4 -4
  115. data/lib/samagotchi/run_options.rb +2 -1
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +244 -0
  118. data/lib/samagotchi/session_access/contract.rb +8 -0
  119. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  120. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  121. data/lib/samagotchi/session_access/exchange.rb +173 -0
  122. data/lib/samagotchi/session_access/local.rb +38 -6
  123. data/lib/samagotchi/session_access/remote.rb +23 -2
  124. data/lib/samagotchi/session_access.rb +1 -0
  125. data/lib/samagotchi/session_chain/delete.rb +39 -81
  126. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  127. data/lib/samagotchi/session_command_catalog.rb +10 -0
  128. data/lib/samagotchi/session_commands.rb +17 -0
  129. data/lib/samagotchi/session_config.rb +4 -4
  130. data/lib/samagotchi/session_delete_command.rb +129 -3
  131. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  132. data/lib/samagotchi/session_manager/listing.rb +4 -4
  133. data/lib/samagotchi/session_manager/removal.rb +38 -12
  134. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  135. data/lib/samagotchi/session_manager.rb +1 -0
  136. data/lib/samagotchi/session_observer.rb +27 -0
  137. data/lib/samagotchi/steer_cut.rb +4 -3
  138. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  139. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  140. data/lib/samagotchi/testing/boundary.rb +4 -0
  141. data/lib/samagotchi/testing/bundle.rb +48 -2
  142. data/lib/samagotchi/testing/fake_http.rb +60 -15
  143. data/lib/samagotchi/testing/host.rb +4 -1
  144. data/lib/samagotchi/testing/recorder.rb +45 -5
  145. data/lib/samagotchi/tools/tool_index.rb +14 -3
  146. data/lib/samagotchi/version.rb +1 -1
  147. data/lib/samagotchi/web/app.rb +20 -6
  148. data/lib/samagotchi/web/ask_routes.rb +292 -0
  149. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  150. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  151. data/lib/samagotchi/web/mcp_route.rb +88 -0
  152. data/lib/samagotchi/web/message_display.rb +6 -1
  153. data/lib/samagotchi/web/participant_view.rb +1 -1
  154. data/lib/samagotchi/web/public/app.js +7 -8
  155. data/lib/samagotchi/web/public/block_fix.js +270 -0
  156. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  157. data/lib/samagotchi/web/public/block_frame.js +77 -13
  158. data/lib/samagotchi/web/public/block_host.js +45 -9
  159. data/lib/samagotchi/web/public/block_regions.js +126 -0
  160. data/lib/samagotchi/web/public/block_renderers.css +12 -0
  161. data/lib/samagotchi/web/public/block_watch.js +16 -2
  162. data/lib/samagotchi/web/public/card.js +22 -9
  163. data/lib/samagotchi/web/public/card_actions.js +21 -0
  164. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  165. data/lib/samagotchi/web/public/card_registry.js +3 -2
  166. data/lib/samagotchi/web/public/data.js +15 -12
  167. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  168. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  169. data/lib/samagotchi/web/public/format.js +3 -0
  170. data/lib/samagotchi/web/public/index.html +52 -7
  171. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  172. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  173. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  174. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  175. data/lib/samagotchi/web/public/refs.js +5 -3
  176. data/lib/samagotchi/web/public/region_hit.js +144 -0
  177. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  178. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  179. data/lib/samagotchi/web/public/session_actions.js +105 -100
  180. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  181. data/lib/samagotchi/web/public/turn_block.js +5 -2
  182. data/lib/samagotchi/web/server.rb +6 -4
  183. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  184. data/lib/samagotchi/web/session_control.rb +84 -30
  185. data/lib/samagotchi/web/session_create.rb +2 -2
  186. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  187. data/lib/samagotchi/worker/child_side.rb +3 -2
  188. data/lib/samagotchi/worker/command_queue.rb +13 -13
  189. data/lib/samagotchi/worker/leave.rb +3 -3
  190. data/lib/samagotchi/worker/scratch.rb +6 -6
  191. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  192. data/lib/samagotchi/worker/startup.rb +3 -3
  193. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  194. data/lib/samagotchi/worker.rb +42 -24
  195. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  196. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  197. data/lib/samagotchi/worker_inbound.rb +12 -7
  198. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  199. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  200. metadata +42 -1
@@ -121,6 +121,9 @@ module Samagotchi
121
121
  "sessions delete --force" => SUPPORTED,
122
122
  "sessions delete --chain" => SUPPORTED,
123
123
  "sessions delete --stop-tasks" => SUPPORTED,
124
+ # A chi web without delete_plan_all (Remote#delete_plan checks its
125
+ # feature) refuses with RemoteTooOld, nothing deleted.
126
+ "sessions delete --dry-run" => SUPPORTED,
124
127
  "sessions prune" => LOCAL_ONLY,
125
128
  "sessions clean" => LOCAL_ONLY,
126
129
  "sessions stats" => LOCAL_ONLY,
@@ -140,6 +143,11 @@ module Samagotchi
140
143
  "share revoke" => SUPPORTED,
141
144
  "share revoke --all" => SUPPORTED,
142
145
 
146
+ # chi as an MCP server (docs/mcp-server.md): its tools over the
147
+ # remote's chi web, as chi send and chi answer.
148
+ "mcp" => SUPPORTED,
149
+ "mcp serve" => SUPPORTED,
150
+
143
151
  "broadcast" => LOCAL_ONLY
144
152
  }.freeze
145
153
 
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Samagotchi
6
+ # Loaded on first use: RunningTasks::Listing.from_wire reads the tasks.
7
+ autoload :SessionManager, File.expand_path("../session_manager", __dir__)
8
+
9
+ module SessionAccess
10
+ # A session's delete plan (SessionChain::Delete::Preview, GET
11
+ # /api/sessions/:id/delete_plan) as chi sessions delete --dry-run reads
12
+ # it, on either backend: Local's hash has symbol keys, the route's JSON
13
+ # string keys, and both are read here only (#read). Each choice says
14
+ # what goes, what is stopped first and what stays (docs/sessions.md,
15
+ # Deleting a link).
16
+ module DeletePlan
17
+ # +chained+ false: no +position+, +size+ or +chain+.
18
+ Plan = Data.define(:session_id, :chained, :position, :size, :link, :chain)
19
+
20
+ # One choice (the link, or the whole chain): +delete+ the delegates'
21
+ # ids that go with it, +leave+ the ones left (Left), +tasks+ the
22
+ # running tasks its delete would meet (RunningTasks::Listing),
23
+ # +workers+ how many of its sessions have a worker and +turns+ how
24
+ # many of those run a turn, +links+ the links it deletes (1 for a
25
+ # link), +previous_id+ the link its undo brings back (nil: none),
26
+ # +moved+ the sessions that go back with it, +refusal+ (Refusal, nil
27
+ # when it can go now).
28
+ Choice = Data.define(:delete, :leave, :tasks, :workers, :turns, :links, :previous_id, :moved, :refusal)
29
+
30
+ # A session the choice leaves: +running+ false for a stopped one left
31
+ # under a running delegate (it stays with it).
32
+ Left = Data.define(:id, :running)
33
+
34
+ # Why the delete can't happen now: +reason+ the refusal's code
35
+ # ("scheduled", "owned_by_tui", …), +message+ its words.
36
+ Refusal = Data.define(:reason, :message)
37
+
38
+ module_function
39
+
40
+ # @param plan [Hash] Preview.call's (symbol keys) or the route's
41
+ # parsed JSON (string keys)
42
+ # @return [Plan]
43
+ def read(plan)
44
+ json = JSON.parse(JSON.generate(plan))
45
+ Plan.new(session_id: json["session_id"].to_s, chained: json["chained"] == true, position: json["position"],
46
+ size: json["size"], link: choice(json["link"], links: 1),
47
+ chain: (choice(json["chain"], links: json.dig("chain", "links").to_i) if json["chain"].is_a?(Hash)))
48
+ end
49
+
50
+ def choice(json, links:)
51
+ json = {} unless json.is_a?(Hash)
52
+ delegates = json["delegates"].is_a?(Hash) ? json["delegates"] : {}
53
+ workers, turns = worker_counts(json["worker"])
54
+ Choice.new(delete: Array(delegates["delete"]).map(&:to_s),
55
+ leave: Array(delegates["leave"]).map { |left| Left.new(id: left["id"].to_s, running: left["running"] == true) },
56
+ tasks: SessionManager::RunningTasks::Listing.from_wire(json["tasks"]),
57
+ workers: workers, turns: turns, links: links, previous_id: json["previous_id"],
58
+ moved: json["moved"].to_i, refusal: refusal(json["refusal"]))
59
+ end
60
+
61
+ # A link's "turn" / "idle" / nil, a chain's {idle: n, turn: n}.
62
+ # @return [Array(Integer, Integer)] workers, turns
63
+ def worker_counts(worker)
64
+ case worker
65
+ when "turn" then [1, 1]
66
+ when "idle" then [1, 0]
67
+ when Hash then [worker["idle"].to_i + worker["turn"].to_i, worker["turn"].to_i]
68
+ else [0, 0]
69
+ end
70
+ end
71
+
72
+ def refusal(json)
73
+ Refusal.new(reason: json["reason"].to_s, message: json["message"].to_s) if json.is_a?(Hash)
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../../session"
5
+ require_relative "../../reply_wait/target"
6
+
7
+ module Samagotchi
8
+ module SessionAccess
9
+ class Exchange
10
+ # A reply wait as one string a thin client carries between two
11
+ # POST …/wait calls: "w1." and the url-safe base64 (no padding) of
12
+ # {s: session_id, t: turn, r: report_turn_id, q: queued, e:
13
+ # ended_before, c: cursor, b: baseline ({messages, question_id,
14
+ # last_turn}) or nil, g: owner_grace}.
15
+ #
16
+ # Unsigned on purpose: every field is one the owner may already put
17
+ # in a POST …/wait body (only the owner's routes take a token);
18
+ # +cursor+ is only compared as a string and never becomes a path, and
19
+ # +turn+ reaches paths only through the ENQUEUED_ID_NAME-guarded
20
+ # helpers (SessionInbox). A token says nothing a body couldn't.
21
+ module Token
22
+ PREFIX = "w1."
23
+ KEYS = %w[s t r q e c b g].freeze
24
+ STRINGS = %w[t r c].freeze
25
+ FLAGS = %w[q e].freeze
26
+ BASELINE_FIELDS = { "messages" => Integer, "question_id" => String, "last_turn" => String }.freeze
27
+ BASELINE_WORDS = "baseline is {messages, question_id, last_turn}"
28
+
29
+ # Anything that isn't a token this chi made: its message says what.
30
+ class Invalid < StandardError; end
31
+
32
+ module_function
33
+
34
+ # @param target [ReplyWait::Target]
35
+ # @return [String]
36
+ def dump(session_id, target)
37
+ fields = { s: session_id, t: target.turn, r: target.report_turn_id, q: target.queued == true,
38
+ e: target.ended_before == true, c: target.cursor, b: target.baseline&.to_h, g: target.owner_grace }
39
+ PREFIX + [JSON.generate(fields)].pack("m0").tr("+/", "-_").delete("=")
40
+ end
41
+
42
+ # @return [Array(String, ReplyWait::Target)] the session id and the wait
43
+ # @raise [Invalid]
44
+ def load(string)
45
+ raise Invalid, "not a wait token" unless string.is_a?(String) && string.start_with?(PREFIX)
46
+
47
+ fields = decode(string.delete_prefix(PREFIX))
48
+ raise Invalid, "a wait token names unknown fields" unless (fields.keys - KEYS).empty?
49
+
50
+ [session_of(fields["s"]), target_of(fields)]
51
+ end
52
+
53
+ # A wait body's or a token's baseline: nil, or a Baseline from
54
+ # exactly its fields, each of its type or null.
55
+ # @return [ReplyWait::Baseline, nil]
56
+ # @raise [Invalid] BASELINE_WORDS
57
+ def baseline(raw)
58
+ return nil if raw.nil?
59
+ unless raw.is_a?(Hash) && raw.all? { |key, value| BASELINE_FIELDS.key?(key) && (value.nil? || value.is_a?(BASELINE_FIELDS[key])) }
60
+ raise Invalid, BASELINE_WORDS
61
+ end
62
+
63
+ ReplyWait::Baseline.new(**raw.transform_keys(&:to_sym))
64
+ end
65
+
66
+ def decode(text)
67
+ raise Invalid, "a wait token is url-safe base64" unless text.match?(/\A[A-Za-z0-9_-]+\z/)
68
+
69
+ padded = text.tr("-_", "+/") + ("=" * ((4 - (text.length % 4)) % 4))
70
+ fields = JSON.parse(padded.unpack1("m0"))
71
+ raise Invalid, "a wait token holds an object" unless fields.is_a?(Hash)
72
+
73
+ fields
74
+ rescue ArgumentError, JSON::ParserError
75
+ raise Invalid, "not a wait token"
76
+ end
77
+
78
+ def session_of(id)
79
+ raise Invalid, "a wait token names its session" unless id.is_a?(String) && Session.valid_id?(id)
80
+
81
+ id
82
+ end
83
+
84
+ def target_of(fields)
85
+ STRINGS.each do |key|
86
+ raise Invalid, "a wait token's #{key} is a string" unless fields[key].nil? || fields[key].is_a?(String)
87
+ end
88
+ FLAGS.each do |key|
89
+ raise Invalid, "a wait token's #{key} is true or false" unless [nil, true, false].include?(fields[key])
90
+ end
91
+ grace = fields["g"]
92
+ raise Invalid, "a wait token's g is positive seconds" unless grace.nil? || (grace.is_a?(Numeric) && grace.positive?)
93
+
94
+ ReplyWait::Target.new(turn: fields["t"], report_turn_id: fields["r"], queued: fields["q"] == true,
95
+ ended_before: fields["e"] == true, cursor: fields["c"], baseline: baseline(fields["b"]),
96
+ owner_grace: grace)
97
+ end
98
+ end
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,173 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../delivery"
4
+ require_relative "../session"
5
+ require_relative "../session_inbox"
6
+ require_relative "../reply_wait/target"
7
+
8
+ module Samagotchi
9
+ module SessionAccess
10
+ # The stateless pieces of "send one message and bind its wait", over a
11
+ # SessionAccess backend (Local or Remote: only their public methods),
12
+ # for every front that sends: chi send (SendCommand, which keeps its
13
+ # retry loop and its lines), chi answer's wait (CLI::ParentWait) and chi
14
+ # web's ask (SessionAccess::Ask). It prints nothing, knows no command
15
+ # name, keeps no state between calls (chi web builds one per request),
16
+ # never retries, and lets the backend's errors raise; it answers values.
17
+ # See docs/internals/remote-sessions.md (Exchange).
18
+ class Exchange
19
+ # How long a send to a link being continued waits for the new link to
20
+ # be saved, and how often it asks again (SendCommand's own constants
21
+ # have the same values, which its specs stub).
22
+ CONTINUING_WAIT = 10.0
23
+ CONTINUING_POLL = 0.2
24
+
25
+ # +given+ named a session: +target+ where input for it goes (a
26
+ # SessionInbox::Resolved), +waited+ whether a continue in flight was
27
+ # waited for on the way.
28
+ Located = Data.define(:target, :waited)
29
+
30
+ # +given+ named no session to send to: +reason+ :continuing (a
31
+ # continue of +asked+, the full id, still in flight past the wait;
32
+ # +message+ its refusal) or :unknown (no such session, or a prefix of
33
+ # several: +error+ the ArgumentError, a Session::AmbiguousId for the
34
+ # latter; +message+ its message).
35
+ Unsent = Data.define(:reason, :message, :asked, :error) do
36
+ def initialize(reason:, message:, asked: nil, error: nil) = super
37
+ end
38
+
39
+ # One delivery made (#attempt): the session as read for it, its
40
+ # +owner+ then, whether it was +running+, the +delivery+ asked for, the
41
+ # image +refs+ copied in and the backend's DeliverResult (+result+:
42
+ # accepted or not, continued or not).
43
+ Attempted = Data.define(:target, :session, :owner, :running, :delivery, :refs, :result)
44
+
45
+ # The caller's check refused the message before anything was sent.
46
+ Stopped = Data.define(:target, :refusal)
47
+
48
+ # @param access [#resolve, #head, #show, #owner, #deliver_turn, #wait_reply] a SessionAccess backend
49
+ # @param pause [#call] sleeps between two looks at a continue in flight
50
+ # @param continuing_wait [Numeric] seconds #locate waits for one
51
+ # @param continuing_poll [Numeric] seconds between two looks
52
+ # @param clock [#call] monotonic seconds
53
+ # @param cancelled [#call] true ends a wait for a continue at the next
54
+ # look (chi web stopping): #locate answers Unsent, #relocate nil
55
+ def initialize(access, pause: ->(seconds) { sleep(seconds) }, continuing_wait: CONTINUING_WAIT,
56
+ continuing_poll: CONTINUING_POLL, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) },
57
+ cancelled: -> { false })
58
+ @access = access
59
+ @pause = pause
60
+ @continuing_wait = continuing_wait
61
+ @continuing_poll = continuing_poll
62
+ @clock = clock
63
+ @cancelled = cancelled
64
+ end
65
+
66
+ # +given+'s session (an id or a prefix), then where input for it goes
67
+ # (the backend's #head): a continued session's chain's newest link. A
68
+ # continue of it in flight (the new link not saved yet) is asked again
69
+ # for up to continuing_wait, then refused; the old link is never
70
+ # named (a send would un-archive it beside the new one).
71
+ # @param deadline [Numeric, nil] this clock's seconds the wait for a
72
+ # continue ends by, if before continuing_wait (an ask's one deadline)
73
+ # @return [Located, Unsent]
74
+ def locate(given, deadline: nil)
75
+ id = @access.resolve(given)
76
+ head = @access.head(id)
77
+ deadline = [@clock.call + @continuing_wait, deadline].compact.min
78
+ waited = head.continuing?
79
+ while head.continuing? && @clock.call < deadline && !@cancelled.call
80
+ pause_until(deadline)
81
+ head = @access.head(id)
82
+ end
83
+ return Unsent.new(reason: :continuing, message: head.continuing_refusal, asked: id) if head.continuing?
84
+
85
+ Located.new(target: head, waited: waited)
86
+ rescue ArgumentError => e
87
+ Unsent.new(reason: :unknown, message: e.message, error: e)
88
+ end
89
+
90
+ # +refused+'s id (its +asked+) located again after a continue took
91
+ # its link (a DeliverResult#continued?), pausing between looks while
92
+ # it still names that link, until +deadline+ (this clock's seconds).
93
+ # @param bounded [Boolean] each look's own wait for a continue ends by
94
+ # +deadline+ too (an ask's one deadline); false, it may wait its
95
+ # continuing_wait past it (chi send's)
96
+ # @yieldparam located [Located] each look that waited on a continue
97
+ # (#locate's waited), whichever link it named
98
+ # @return [Located, Unsent, nil] nil: out of time
99
+ def relocate(refused, deadline, bounded: false)
100
+ while @clock.call < deadline && !@cancelled.call
101
+ pause_until(deadline)
102
+ again = locate(refused.asked, deadline: (deadline if bounded))
103
+ return again unless again.is_a?(Located)
104
+
105
+ yield again if block_given? && again.waited
106
+ next if again.target.id == refused.id
107
+
108
+ return again
109
+ end
110
+ nil
111
+ end
112
+
113
+ # One delivery of +prompt+ to +target+: the session read, +check+
114
+ # (a String refuses: nothing is sent), its owner, the images copied
115
+ # in, then the turn. +queue+ always goes as a queue, idle or not;
116
+ # +cut+ asks a running turn for a cut (an idle session's is an
117
+ # ordinary message). No retry and no discard: a continued result is
118
+ # returned as is, and the caller takes its refs back and relocates.
119
+ # @param images [#upload, nil] answers upload(id) with the refs a turn
120
+ # takes (nil: none)
121
+ # @param check [#call, nil] called with the session read: a refusal
122
+ # String, or nil to go on
123
+ # @return [Attempted, Stopped]
124
+ def attempt(target, prompt, client_id:, queue: false, cut: false, images: nil, check: nil)
125
+ id = target.id
126
+ session = @access.show(id)
127
+ if check && (refusal = check.call(session))
128
+ return Stopped.new(target: target, refusal: refusal)
129
+ end
130
+
131
+ owner = @access.owner(id)
132
+ running = owner && session.status == Session::STATUS_RUNNING
133
+ refs = images ? images.upload(id) : []
134
+ delivery = if queue then Delivery::QUEUE
135
+ elsif cut && running then Delivery::CUT
136
+ end
137
+ result = @access.deliver_turn(id, prompt: prompt, client_id: client_id, images: refs, delivery: delivery,
138
+ follow: target.via != :pinned)
139
+ Attempted.new(target: target, session: session, owner: owner, running: running, delivery: delivery, refs: refs,
140
+ result: result)
141
+ end
142
+
143
+ # The wait for an accepted message's own turn (ReplyWait::Target.message).
144
+ # @param start [WaitStart] prepare_wait's, read before it went in
145
+ def bind(start, result, queue:) = ReplyWait::Target.message(start, result, queue: queue)
146
+
147
+ # The backend's wait for what +target+ binds: the result's turn_id is
148
+ # the target's report_turn_id whenever that is known (even when the
149
+ # wait took the next reply), its text UTF-8.
150
+ # @param more [Hash] passed on (cancelled: for a Local backend)
151
+ # @return [ReplyWait::Result]
152
+ # @raise [ArgumentError] the session is gone
153
+ def wait(id, target, timeout:, poll_interval: nil, **more)
154
+ options = { timeout: timeout, **more }
155
+ options[:poll_interval] = poll_interval if poll_interval
156
+ result = @access.wait_reply(id, **target.to_h, **options)
157
+ report_turn_id = target.report_turn_id
158
+ result.turn_id = report_turn_id if report_turn_id && !report_turn_id.to_s.empty?
159
+ result.text = result.text&.dup&.force_encoding(Encoding::UTF_8)&.scrub
160
+ result
161
+ end
162
+
163
+ # This exchange's clock, for a caller's deadline (#relocate's).
164
+ def now = @clock.call
165
+
166
+ private
167
+
168
+ # One pause between two looks: continuing_poll, or less when
169
+ # +deadline+ comes first.
170
+ def pause_until(deadline) = @pause.call([@continuing_poll, deadline - @clock.call].min)
171
+ end
172
+ end
173
+ end
@@ -191,9 +191,15 @@ module Samagotchi
191
191
  # @return [SessionManager::DeliverResult]
192
192
  # @raise [SessionManager::OwnedByTUI] a one-turn chi run owns it
193
193
  # @param follow [Boolean] +id+ is the head #head resolved (SessionManager.deliver_turn's follow:)
194
- def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false)
194
+ # @param manager [#resume_session, nil] the manager that starts its
195
+ # worker; nil: SessionManager's own default
196
+ # @param bridge [#call, nil] the worker's Bridge client (chi web's
197
+ # live_bridge_client: POST …/ask delivers as POST …/turn does); nil:
198
+ # 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
195
201
  SessionManager.deliver_turn(id, prompt: prompt, client_id: client_id, images: images, delivery: delivery,
196
- follow: follow, **dir)
202
+ follow: follow, **routing, **dir)
197
203
  end
198
204
 
199
205
  # @return [NoteDelivery::Result]
@@ -266,11 +272,16 @@ module Samagotchi
266
272
 
267
273
  # The answer posted to the session's worker (its Bridge), once more
268
274
  # after a 408.
275
+ # @param within [Numeric, nil] the most seconds for it all (an MCP
276
+ # call's, under its host's limit): each try's read timeout is cut
277
+ # to it, and a 408 is tried again only when a whole try still fits
269
278
  # @return [BridgeClient::Response, nil] the Bridge's reply; nil when
270
279
  # no worker runs it
271
280
  # @raise [SystemCallError, IOError, SocketError] the worker went away
272
- def answer(id, question_id:, selected:, freeform:, client_id:)
273
- on_worker(id) { |client| client.answer(id: question_id, selected: selected, freeform: freeform, client_id: client_id) }
281
+ def answer(id, question_id:, selected:, freeform:, client_id:, within: nil)
282
+ on_worker(id, within: within) do |client|
283
+ client.answer(id: question_id, selected: selected, freeform: freeform, client_id: client_id)
284
+ end
274
285
  end
275
286
 
276
287
  # The question dismissed on the session's worker; as #answer.
@@ -310,6 +321,19 @@ module Samagotchi
310
321
  SessionManager.delete_chain(id, stop: force, running_tasks: tasks_policy(stop_tasks), **dir)
311
322
  end
312
323
 
324
+ # What #delete (+chain+: #delete_chain) would do now, deleting
325
+ # nothing (chi sessions delete --dry-run): the web sheet's plan.
326
+ # A folder whose session file is gone has a plan too (chi web's
327
+ # route answers for it); neither on disk is no session.
328
+ # @return [DeletePlan::Plan]
329
+ # @raise [Session::NotFound]
330
+ def delete_plan(id)
331
+ raise Session::NotFound, id unless File.exist?(Session.session_file(id, state_dir: state_dir!)) || Dir.exist?(session_dir(id))
332
+
333
+ require_relative "../session_chain/delete_preview"
334
+ DeletePlan.read(SessionChain::Delete::Preview.call(id, state_dir: state_dir!))
335
+ end
336
+
313
337
  # A user's delete or archive: REFUSE, or a stop by "user".
314
338
  private def tasks_policy(stop_tasks)
315
339
  policies = SessionManager::RunningTasks::Policy
@@ -616,15 +640,23 @@ module Samagotchi
616
640
 
617
641
  # The block's post to the session's live worker, again on a 408 (the
618
642
  # worker didn't take it in time).
619
- def on_worker(id)
620
- client = WorkerLink.client(id, session_dir: session_dir(id)) or return nil
643
+ # The shortest read timeout a cut try gets (#on_worker's within:).
644
+ MIN_TRY = 1.0
645
+
646
+ def on_worker(id, within: nil)
647
+ limit = within ? within.to_f.clamp(MIN_TRY, BridgeClient::READ_TIMEOUT.to_f) : BridgeClient::READ_TIMEOUT
648
+ client = WorkerLink.client(id, session_dir: session_dir(id), read_timeout: limit) or return nil
649
+ ends = monotonic + within if within
621
650
  reply = nil
622
651
  2.times do
623
652
  reply = yield client
624
653
  break unless reply.status == 408
654
+ break if ends && monotonic + limit > ends
625
655
  end
626
656
  reply
627
657
  end
658
+
659
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
628
660
  end
629
661
  end
630
662
  end
@@ -320,6 +320,9 @@ module Samagotchi
320
320
  CHAIN_DELETE_FEATURE = "chain_delete"
321
321
  # Web::App::STOP_TASKS_FEATURE: delete and archive take stop_tasks.
322
322
  STOP_TASKS_FEATURE = "stop_tasks"
323
+ # Web::App::DELETE_PLAN_FEATURE: GET …/delete_plan answers for every
324
+ # session, with each choice's delegates, tasks and workers.
325
+ DELETE_PLAN_FEATURE = "delete_plan_all"
323
326
 
324
327
  # The header that chi web names the signed-in user in (GET
325
328
  # /api/info's proxy), nil when it has no such proxy, or is a chi
@@ -446,8 +449,11 @@ module Samagotchi
446
449
 
447
450
  # The answer, through chi web to the session's worker. chi web's
448
451
  # answers mapped back to the Bridge's own (AnswerCommand reads those).
452
+ # @param within [nil, Numeric] not cut here: chi web's route bounds its
453
+ # own tries, and a request cut short might still have answered (Local's
454
+ # cut is for an MCP host's 60 s limit on HTTP; this runs under stdio)
449
455
  # @return [BridgeClient::Response, nil] nil when no worker runs it
450
- def answer(id, question_id:, selected:, freeform:, client_id:)
456
+ def answer(id, question_id:, selected:, freeform:, client_id:, within: nil)
451
457
  bridge_reply(request(:post, "#{session_path(id)}/answer",
452
458
  body: { id: question_id, selected: selected, freeform: freeform, client_id: client_id }))
453
459
  end
@@ -538,6 +544,19 @@ module Samagotchi
538
544
  **task_fields(json) }
539
545
  end
540
546
 
547
+ # GET …/delete_plan there: what a delete would do now (chi sessions
548
+ # delete --dry-run), nothing deleted.
549
+ # @return [DeletePlan::Plan]
550
+ # @raise [RemoteTooOld] a chi web without DELETE_PLAN_FEATURE (an
551
+ # older one answers a session in no chain without the plan)
552
+ def delete_plan(id)
553
+ require_feature!(DELETE_PLAN_FEATURE)
554
+ reply = request(:get, "#{session_path(id)}/delete_plan")
555
+ raise_refusal(reply) unless reply.status == 200
556
+
557
+ DeletePlan.read(reply.json)
558
+ end
559
+
541
560
  private def ids_of(value) = Array(value).select { |id| Session.valid_id?(id) }
542
561
 
543
562
  # --- context (a session's own sources: a project's are local only)
@@ -841,7 +860,9 @@ module Samagotchi
841
860
  # Whose worker was stopped (an older chi web sends only the Boolean).
842
861
  stopped = Session.valid_id?(json["stopped_worker"]) ? json["stopped_worker"] : json["worker_stopped"] == true
843
862
  if json["op"] == "archive"
844
- SessionManager::ArchiveRefused.new(sid, :tasks_running, tasks: tasks, worker_stopped: stopped)
863
+ stopped_workers = Array(json["stopped_workers"]).select { |id| id.is_a?(String) && Session.valid_id?(id) }
864
+ SessionManager::ArchiveRefused.new(sid, :tasks_running, tasks: tasks, worker_stopped: stopped,
865
+ sessions: json["sessions"], stopped_workers: stopped_workers)
845
866
  else
846
867
  SessionManager::DeleteRefused.new(sid, :tasks_running, tasks: tasks, worker_stopped: stopped,
847
868
  links: ids_of(json["links"]))
@@ -18,6 +18,7 @@ module Samagotchi
18
18
  autoload :Contract, File.expand_path("session_access/contract", __dir__)
19
19
  autoload :Remote, File.expand_path("session_access/remote", __dir__)
20
20
  autoload :Dispatch, File.expand_path("session_access/dispatch", __dir__)
21
+ autoload :DeletePlan, File.expand_path("session_access/delete_plan", __dir__)
21
22
 
22
23
  # A remote's chi web could not be asked, or answered what this chi can't
23
24
  # use: the message names the remote and what failed ("remote studio