samagotchi 0.184.0 → 0.186.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 (119) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/docs/architecture.md +1 -1
  4. data/docs/bundles.md +62 -35
  5. data/docs/cli.md +10 -1
  6. data/docs/configuration.md +19 -1
  7. data/docs/context.md +76 -10
  8. data/docs/guardrails.md +20 -2
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/block-renderers.md +4 -2
  11. data/docs/internals/bridge.md +7 -2
  12. data/docs/internals/engine.md +15 -1
  13. data/docs/internals/llm-context-forget.md +6 -0
  14. data/docs/internals/participants.md +4 -1
  15. data/docs/internals/prompt-caching.md +14 -0
  16. data/docs/internals/remote-sessions.md +10 -1
  17. data/docs/internals/session-lifecycle.md +1 -1
  18. data/docs/internals/web-frontend.md +23 -6
  19. data/docs/mcp-server.md +6 -2
  20. data/docs/scheduling.md +5 -0
  21. data/docs/sessions.md +12 -2
  22. data/docs/sub-agent.md +48 -3
  23. data/docs/thin-clients.md +76 -4
  24. data/lib/samagotchi/agent_caller.rb +97 -0
  25. data/lib/samagotchi/bridge.rb +7 -7
  26. data/lib/samagotchi/bundles/claude-peer/manifest.yml +14 -8
  27. data/lib/samagotchi/bundles/claude-peer/plugin.rb +3 -3
  28. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +49 -30
  29. data/lib/samagotchi/bundles/claude-peer/scripts/pair +2 -2
  30. data/lib/samagotchi/bundles/claude-peer/scripts/pair-remote +123 -0
  31. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +11 -3
  32. data/lib/samagotchi/bundles/codex-peer/manifest.yml +10 -8
  33. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  34. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +29 -8
  35. data/lib/samagotchi/bundles/codex-peer/scripts/pair +1 -1
  36. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +11 -3
  37. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  38. data/lib/samagotchi/bundles/mcp/http_client.rb +19 -2
  39. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  40. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  41. data/lib/samagotchi/bundles/system/self_map.md +2 -0
  42. data/lib/samagotchi/client_id.rb +61 -1
  43. data/lib/samagotchi/command_intake.rb +16 -8
  44. data/lib/samagotchi/config.rb +3 -1
  45. data/lib/samagotchi/context_absorber.rb +215 -46
  46. data/lib/samagotchi/delivery.rb +15 -0
  47. data/lib/samagotchi/driver_command.rb +68 -0
  48. data/lib/samagotchi/engine/block_fix.rb +2 -2
  49. data/lib/samagotchi/engine.rb +20 -5
  50. data/lib/samagotchi/engine_peers.rb +6 -0
  51. data/lib/samagotchi/guardrails/pair_boundary.rb +1 -1
  52. data/lib/samagotchi/llm/chat_loop.rb +16 -2
  53. data/lib/samagotchi/mcp_command.rb +7 -2
  54. data/lib/samagotchi/mcp_server/tools.rb +9 -3
  55. data/lib/samagotchi/objectives_track.rb +2 -1
  56. data/lib/samagotchi/owner_prompt.rb +5 -1
  57. data/lib/samagotchi/parent_report.rb +9 -5
  58. data/lib/samagotchi/plain_reply.rb +75 -0
  59. data/lib/samagotchi/plugin/peer.rb +10 -4
  60. data/lib/samagotchi/reply_for.rb +254 -0
  61. data/lib/samagotchi/reply_wait.rb +12 -3
  62. data/lib/samagotchi/schedules.rb +10 -7
  63. data/lib/samagotchi/send_command/parent_gate.rb +3 -1
  64. data/lib/samagotchi/send_command.rb +45 -8
  65. data/lib/samagotchi/session.rb +9 -1
  66. data/lib/samagotchi/session_access/ask.rb +10 -4
  67. data/lib/samagotchi/session_access/contract.rb +2 -0
  68. data/lib/samagotchi/session_access/exchange/token.rb +42 -7
  69. data/lib/samagotchi/session_access/exchange.rb +5 -2
  70. data/lib/samagotchi/session_access/local.rb +6 -3
  71. data/lib/samagotchi/session_access/remote.rb +23 -3
  72. data/lib/samagotchi/session_access.rb +4 -2
  73. data/lib/samagotchi/session_command_catalog.rb +8 -0
  74. data/lib/samagotchi/session_commands.rb +9 -0
  75. data/lib/samagotchi/session_continue.rb +4 -1
  76. data/lib/samagotchi/session_inbox.rb +2 -0
  77. data/lib/samagotchi/session_inbox_delivery.rb +4 -2
  78. data/lib/samagotchi/session_manager/delivery.rb +80 -5
  79. data/lib/samagotchi/session_manager/spawn.rb +7 -1
  80. data/lib/samagotchi/steer.rb +119 -22
  81. data/lib/samagotchi/terminal_ui/formatting.rb +12 -2
  82. data/lib/samagotchi/tool_activity.rb +4 -0
  83. data/lib/samagotchi/tool_declarations.rb +22 -1
  84. data/lib/samagotchi/tool_names.rb +4 -0
  85. data/lib/samagotchi/toolkit.rb +3 -2
  86. data/lib/samagotchi/tools/ask_session.rb +208 -0
  87. data/lib/samagotchi/tools/builtin_calls.rb +1 -0
  88. data/lib/samagotchi/tools/builtins.rb +5 -0
  89. data/lib/samagotchi/turn_anchors.rb +65 -17
  90. data/lib/samagotchi/turn_checkpoint.rb +21 -2
  91. data/lib/samagotchi/turn_stages/context_judge.rb +3 -1
  92. data/lib/samagotchi/turn_stages/objectives.rb +4 -2
  93. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +3 -0
  94. data/lib/samagotchi/version.rb +1 -1
  95. data/lib/samagotchi/visitor.rb +37 -0
  96. data/lib/samagotchi/web/app.rb +1 -1
  97. data/lib/samagotchi/web/ask_routes.rb +68 -21
  98. data/lib/samagotchi/web/message_display.rb +15 -2
  99. data/lib/samagotchi/web/participant_access.rb +1 -1
  100. data/lib/samagotchi/web/public/app.js +1 -1
  101. data/lib/samagotchi/web/public/block_fix.js +11 -3
  102. data/lib/samagotchi/web/public/history_shape.js +3 -1
  103. data/lib/samagotchi/web/public/index.html +8 -0
  104. data/lib/samagotchi/web/public/peer_links.js +27 -4
  105. data/lib/samagotchi/web/public/peer_note.js +19 -3
  106. data/lib/samagotchi/web/public/peer_text.js +62 -0
  107. data/lib/samagotchi/web/public/picture_regions.js +2 -2
  108. data/lib/samagotchi/web/public/turn_events.js +19 -0
  109. data/lib/samagotchi/web/public/working_set_view.js +11 -2
  110. data/lib/samagotchi/web/session_access_routes.rb +30 -2
  111. data/lib/samagotchi/web/session_control.rb +22 -3
  112. data/lib/samagotchi/web/session_create.rb +11 -7
  113. data/lib/samagotchi/worker/command_queue.rb +5 -2
  114. data/lib/samagotchi/worker/senders.rb +79 -0
  115. data/lib/samagotchi/worker.rb +22 -18
  116. data/lib/samagotchi/worker_inbound.rb +12 -4
  117. data/lib/samagotchi/worker_participant_gate.rb +1 -3
  118. data/lib/samagotchi/worker_wakes.rb +12 -0
  119. metadata +10 -1
@@ -17,6 +17,7 @@ require_relative "turn_endings"
17
17
  require_relative "turn_origin"
18
18
  require_relative "revise_anchor"
19
19
  require_relative "verify_anchor"
20
+ require_relative "reply_for"
20
21
  require_relative "redact"
21
22
  require_relative "verdict"
22
23
  require_relative "model_profile"
@@ -423,9 +424,10 @@ module Samagotchi
423
424
  # The tools a scratch session doesn't offer, and its memory_write.
424
425
  def restrict_scratch_tools!
425
426
  # A scratch session's children would outlive it, and so would a
426
- # note it left in a peer; its memories would too (write and edit
427
- # into the memories: ScratchWrites).
428
- [Tools::Delegate::NAME, Tools::DelegateResult::NAME, Tools::SendNote::NAME].each { |name| @tools.unregister(name) }
427
+ # note it left in a peer or a question's turn; its memories would too
428
+ # (write and edit into the memories: ScratchWrites).
429
+ [Tools::Delegate::NAME, Tools::DelegateResult::NAME, Tools::SendNote::NAME,
430
+ Tools::AskSession::NAME].each { |name| @tools.unregister(name) }
429
431
  @tools[Tools::MemoryWrite::NAME].handler = ->(_call, _kctx) { SCRATCH_MEMORY_WRITE }
430
432
  end
431
433
  private :restrict_scratch_tools!
@@ -857,8 +859,12 @@ module Samagotchi
857
859
  # +history_size+: turn.messages' size under the system head, before
858
860
  # the reminders and the prompt (#turn_messages): where the turn's own
859
861
  # messages start in what it keeps (the end event's kept_from).
862
+ # +opener_source+: the sender its prompt is saved with (the opener's
863
+ # source, Steer::OPENER_HEADERS), nil for the owner's (no source).
864
+ # +reply_for+: the surface its reply is for (ReplyFor), nil for full.
860
865
  Turn = Struct.new(:context, :prompt, :continue, :on_event, :started_at, :messages, :ended, :prepared_settings,
861
- :limit, :resumed, :resume_from, :wall, :verify, :revises, :outcome, :history_size) do
866
+ :limit, :resumed, :resume_from, :wall, :verify, :revises, :outcome, :history_size,
867
+ :opener_source, :reply_for) do
862
868
  # The turn's id (:turn_started's turn_id, its metrics record's id and
863
869
  # its saved prompt's), session, origin and controller: its context's.
864
870
  def id = context.id
@@ -937,6 +943,8 @@ module Samagotchi
937
943
  # @param verify [VerifyAnchor, nil] a Verify turn's claim (its verdict)
938
944
  # @param revises [ReviseAnchor, nil] a Revise turn's draft: stamped on
939
945
  # the prompt at the turn's end, metadata only (TurnStages::VerifyAnchors#stamp_opening)
946
+ # @param reply_for [ReplyFor, Hash, nil] what the asking surface shows:
947
+ # saved on the prompt with its baked line (ReplyFor.opener_fields)
940
948
  #
941
949
  # An Interrupt (SIGINT) cancels the turn: what it got to is kept in the
942
950
  # session as after a Stop (the prompt, the loop's finished tool
@@ -949,10 +957,12 @@ module Samagotchi
949
957
  # one-line summary:.
950
958
  def run_turn(session, prompt, on_event: nil, max_iterations: nil, cancel_controller: nil, max_tool_output_chars: nil, pending_input: nil, continue: false,
951
959
  origin: TurnOrigin::NONE, images: [], id: nil, resumed: false, resume_from: nil, verify: nil, revises: nil,
952
- input_waiting: nil)
960
+ input_waiting: nil, opener_source: nil, reply_for: nil)
953
961
  turn = begin_turn(session, prompt, on_event: on_event, cancel_controller: cancel_controller, origin: origin,
954
962
  continue: continue, id: id, verify: verify, revises: revises,
955
963
  input_waiting: input_waiting)
964
+ turn.opener_source = opener_source.to_s unless opener_source.to_s.empty?
965
+ turn.reply_for = ReplyFor.from(reply_for)
956
966
  if continue
957
967
  turn.resumed = resumed
958
968
  turn.resume_from = resume_from
@@ -1204,6 +1214,11 @@ module Samagotchi
1204
1214
  **participant_mode_fields(turn.context), MessageTime::KEY => turn.at }
1205
1215
  user_message[:verify] = turn.verify.to_h if turn.verify
1206
1216
  user_message[:images] = image_refs unless image_refs.empty?
1217
+ # Only an opener from a sender the model reads a header for
1218
+ # (Steer::OPENER_HEADERS): the owner's keeps its bytes.
1219
+ user_message[:source] = turn.opener_source if turn.opener_source
1220
+ # The surface's values and the line the model reads (none: its bytes as they were).
1221
+ user_message.merge!(ReplyFor.opener_fields(session.messages, turn.reply_for))
1207
1222
  turn.messages << user_message
1208
1223
  session.last_prompt = turn.prompt
1209
1224
  end
@@ -7,6 +7,10 @@ module Samagotchi
7
7
  # (KernelLoop::Services#peers, Engine#wire_kernel) and a delegate's approval relay
8
8
  # (Engine#relay_peer).
9
9
  class Engine
10
+ # The running turn's id as other threads see it (TurnState), nil
11
+ # between turns: what PeerView#turn_id reads.
12
+ def running_turn_id = @turn_state.context&.id
13
+
10
14
  # The kernel's Tools::Peers, following the current session. cancelled?
11
15
  # is the running turn's cancel, for a tool that waits (delegate_result):
12
16
  # the controller is set from another thread and a tool gets no other
@@ -15,6 +19,8 @@ module Samagotchi
15
19
  # return on it, execute hands its command over early).
16
20
  PeerView = Struct.new(:engine) do
17
21
  def session_id = engine.session&.id
22
+ # The running turn's id (ask_session's request_id), nil between turns.
23
+ def turn_id = engine.running_turn_id
18
24
  def cwd = engine.session&.working_directory
19
25
  def project_root = engine.session&.project_root
20
26
  def project_id = engine.session&.project_id
@@ -51,7 +51,7 @@ module Samagotchi
51
51
  class PairBoundary
52
52
  RULE = "pair-boundary"
53
53
  SOURCE = "core"
54
- OWNER_VOICED = %w[delegate register_reminder cancel_reminder send_note forget_outputs task_create task_stop
54
+ OWNER_VOICED = %w[delegate register_reminder cancel_reminder send_note ask_session forget_outputs task_create task_stop
55
55
  find_tools objectives schedule_task list_schedules cancel_schedule].freeze
56
56
  OWNER_VOICED_PREFIX = "delegate_"
57
57
  # The background task tools that read the owner's tasks (a pair turn
@@ -21,6 +21,7 @@ require_relative "../cut_policy"
21
21
  require_relative "../context_status"
22
22
  require_relative "../context_window"
23
23
  require_relative "../context_note"
24
+ require_relative "../reply_for"
24
25
  require_relative "../tool_output_cut"
25
26
  require_relative "../tool_runner"
26
27
  require_relative "../tool_response"
@@ -261,8 +262,9 @@ module Samagotchi
261
262
  wire << system_message(entry, index)
262
263
  end
263
264
  when "user"
264
- # A steer or merged input (always a String) goes with its header.
265
- content = Steer.header(entry) ? Steer.wire_text(entry, entry[:content].to_s) : entry[:content]
265
+ # A steer or merged input (always a String) goes with its header,
266
+ # an opener with its header or its reply line (Steer.wire_text).
267
+ content = Steer.header(entry) || Steer.reply_line(entry) ? Steer.wire_text(entry, entry[:content].to_s) : entry[:content]
266
268
  wire << { role: "user", content: parts(content, items) }
267
269
  when "model"
268
270
  message = assistant_message(entry, paired)
@@ -478,6 +480,15 @@ module Samagotchi
478
480
  # find_tools result's loaded names and a tool change's TOOL_CHANGE
479
481
  # (sent only to a wire that loads tools), and an entry's wall time
480
482
  # (MessageTime::KEY, display-only, never sent).
483
+ #
484
+ # The rule: a saved message field the wire needs must be listed here
485
+ # (a key below, or one of the lists it reads: ContextNote::KEYS,
486
+ # Steer::AUTHOR_KEYS, ToolResponse::SAVED_KEYS). This rebuilds every
487
+ # kept message, earlier turns' included, from these keys alone: an
488
+ # unlisted field is gone from the saved history once its turn ends,
489
+ # so the next request reads that message without it and the chat
490
+ # wires' prompt prefix breaks (a visitor opener's +source+ header,
491
+ # say). spec/llm/chat_loop_saved_keys_spec.rb fails on such a field.
481
492
  def plain(conversation)
482
493
  conversation.map do |entry|
483
494
  content = entry[:content].is_a?(Array) ? entry[:content] : entry[:content].to_s
@@ -490,6 +501,9 @@ module Samagotchi
490
501
  message[:turn_start] = true if entry[:turn_start] == true
491
502
  message[:verify] = entry[:verify] if entry[:verify].is_a?(Hash)
492
503
  message[:revises] = entry[:revises] if entry[:revises].is_a?(Hash)
504
+ # An opener's surface (ReplyFor) and the line baked from it, which the wire reads.
505
+ message[ReplyFor::MESSAGE_KEY] = entry[ReplyFor::MESSAGE_KEY] if entry[ReplyFor::MESSAGE_KEY].is_a?(Hash)
506
+ message[ReplyFor::LINE_KEY] = entry[ReplyFor::LINE_KEY] if entry[ReplyFor::LINE_KEY].is_a?(String)
493
507
  message[:thinking] = entry[:thinking] if entry[:thinking].is_a?(String) && !entry[:thinking].empty?
494
508
  message[:anthropic_content] = entry[:anthropic_content] if entry[:anthropic_content].is_a?(Array)
495
509
  ToolResponse::SAVED_KEYS.each { |key| message[key] = entry[key] if entry[key] }
@@ -33,8 +33,10 @@ module Samagotchi
33
33
 
34
34
  # @param access [SessionAccess::Local, SessionAccess::Remote, nil]
35
35
  # where the sessions are; default this machine's, in +state_dir+
36
- def initialize(argv, access: nil, stdin: $stdin, stdout: $stdout, stderr: $stderr, state_dir: nil)
36
+ # @param env [Hash] where the agent markers are read (ENV; specs pass their own)
37
+ def initialize(argv, access: nil, stdin: $stdin, stdout: $stdout, stderr: $stderr, state_dir: nil, env: ENV)
37
38
  @argv = argv.dup
39
+ @env = env
38
40
  @access = access
39
41
  @stdin = stdin
40
42
  @stdout = stdout
@@ -73,12 +75,15 @@ module Samagotchi
73
75
 
74
76
  def build_tools
75
77
  require_relative "mcp_server/tools"
78
+ require_relative "agent_caller"
76
79
  access = @access || begin
77
80
  require_relative "session_access/local"
78
81
  SessionAccess::Local.new(state_dir: @state_dir)
79
82
  end
80
83
  load_for_calls unless access.remote?
81
- McpServer::Tools.new(access)
84
+ # The host's agent marker names its messages (CLAUDECODE: claude), else
85
+ # "mcp" (AgentCaller).
86
+ McpServer::Tools.new(access, agent: AgentCaller.name(env: @env) || McpServer::Tools::DEFAULT_AGENT)
82
87
  end
83
88
 
84
89
  def load_for_calls
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../agent_caller"
3
4
  require_relative "../client_id"
4
5
  require_relative "../session_inbox"
5
6
  require_relative "../turn_flow"
@@ -22,6 +23,8 @@ module Samagotchi
22
23
  # Seconds one call waits before it answers "still running" (spike D2:
23
24
  # well inside Claude Code HTTP's 60 s and Codex's 300 s).
24
25
  SLICE = 25
26
+ # The agent an MCP host's messages go as when nothing names it.
27
+ DEFAULT_AGENT = "mcp"
25
28
  # The most seconds a chi_ask or a chi_answer takes in all
26
29
  # (Web::AskRoutes::ASK_MAX_SECONDS); under --remote about a minute for
27
30
  # a slow worker (the other chi web's routes make their own tries).
@@ -73,8 +76,11 @@ module Samagotchi
73
76
  # @param cap [Numeric] seconds a chi_ask or chi_answer takes in all (CAP)
74
77
  # @param exchange [#call, nil] (access) -> the Exchange a call uses
75
78
  # (chi web's carries its stop check); nil: a plain one
76
- def initialize(access, slice: SLICE, cap: CAP, exchange: nil, cancelled: nil)
79
+ # @param agent [String] the name its messages go as (agent:<name>):
80
+ # the host's marker on stdio (McpCommand), "mcp" over HTTP
81
+ def initialize(access, slice: SLICE, cap: CAP, exchange: nil, cancelled: nil, agent: DEFAULT_AGENT)
77
82
  @access = access
83
+ @agent = agent
78
84
  @slice = slice
79
85
  @cap = cap
80
86
  @exchange = exchange || ->(backend) { SessionAccess::Exchange.new(backend) }
@@ -169,9 +175,9 @@ module Samagotchi
169
175
  # parent_answers of the session asked and its chain's newest link; on
170
176
  # a remote chi web's turn route gates the same ids itself.
171
177
  def sender(asker, given, prompt)
172
- return TurnFlow.continue_yes?(prompt) ? ClientId::CLI_ANSWER : ClientId::CLI_SEND if @access.remote?
178
+ return TurnFlow.continue_yes?(prompt) ? ClientId::CLI_ANSWER : AgentCaller.send_id(name: @agent) if @access.remote?
173
179
 
174
- asker.agent_line(prompt, session: targets(given))
180
+ asker.agent_line(prompt, session: targets(given), name: @agent)
175
181
  end
176
182
 
177
183
  def targets(given)
@@ -15,6 +15,7 @@ require_relative "owner_prompt"
15
15
  require_relative "session"
16
16
  require_relative "steer"
17
17
  require_relative "tools/objectives_tool"
18
+ require_relative "visitor"
18
19
 
19
20
  module Samagotchi
20
21
  autoload :Objectives, File.expand_path("objectives", __dir__)
@@ -107,7 +108,7 @@ module Samagotchi
107
108
  session = turn.session
108
109
  return false unless active?(Objectives.current(session.id, session.messages, state_dir: engine.session_state_dir))
109
110
  return false if engine.interface == :non_interactive
110
- return false unless OwnerPrompt.turn?(author: turn.origin.author)
111
+ return false unless OwnerPrompt.turn?(author: turn.origin.author) && !Visitor.of?(turn.origin.client_id, session)
111
112
 
112
113
  worked_without_move?(session.messages)
113
114
  end
@@ -14,16 +14,20 @@ module Samagotchi
14
14
  # carries the turn's id), or TurnCheckpoint's line for a turn killed
15
15
  # before its first boundary (stamped, no id). A !command's output, a
16
16
  # declined continue's reason and KernelLoop's recovery prompt are
17
- # neither; steers, notes and reminders carry their kind.
17
+ # neither; steers, notes and reminders carry their kind. A visitor's
18
+ # opener (an agent's in a session it doesn't drive) carries its source.
18
19
  def message?(message)
19
20
  field(message, :role).to_s == "user" &&
20
21
  !Steer.participant_author?(field(message, :author)) &&
22
+ !(field(message, :kind).to_s.empty? && !field(message, :source).to_s.empty?) &&
21
23
  !%w[input steer note reminder].include?(field(message, :kind).to_s) &&
22
24
  !field(message, :preserve_literals) &&
23
25
  !(field(message, :turn_id) || field(message, MessageTime::KEY)).nil?
24
26
  end
25
27
 
26
28
  # Whether a turn by +author+ is the owner's own: not a participant's.
29
+ # The callers ask Visitor.of? beside it, for a visitor's turn (its
30
+ # origin's client id).
27
31
  def turn?(author:) = !Steer.participant_author?(author)
28
32
 
29
33
  def field(hash, key)
@@ -75,14 +75,18 @@ module Samagotchi
75
75
  end
76
76
  end
77
77
 
78
- # The reasons a worker refuses a participant's queued turn
79
- # (WorkerParticipantGate#refusal), as its settled record's cancel_reason.
78
+ # The reasons a worker refuses a queued turn before it runs, as its
79
+ # settled record's cancel_reason: a participant's
80
+ # (WorkerParticipantGate#refusal), and a visitor's at session.max_wakes
81
+ # (Worker#refuse_visitor, Visitor::CAP_REASON).
80
82
  REFUSED_LINES = { "revoked" => ParticipantMessages::TOKEN_ENDED,
81
83
  "outdated" => ParticipantMessages::TOKEN_OUTDATED,
82
- "cap_reached" => ParticipantMessages::CAP_REACHED }.freeze
84
+ "cap_reached" => ParticipantMessages::CAP_REACHED,
85
+ "max_wakes" => "session.max_wakes turns ran in a row with no message from this session's owner; " \
86
+ "it runs again after their next message" }.freeze
83
87
 
84
- # A participant's turn the worker refused before it ran: by its
85
- # cancel_reason (chi web's participant wait sends no outcome).
88
+ # A participant's or a visitor's turn the worker refused before it ran:
89
+ # by its cancel_reason (chi web's participant wait sends no outcome).
86
90
  def refused?(result)
87
91
  result.status == :no_reply && REFUSED_LINES.key?(result.cancel_reason.to_s) &&
88
92
  [nil, "canceled"].include?(result.outcome)
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ # A reply made plain for a surface that shows plain text only (ReplyFor
5
+ # formatting "plain": a voice Shortcut reads it aloud). Deterministic: the
6
+ # same text gives the same output. On the way out only, in chi web's wait
7
+ # answers (SessionAccessRoutes#wait_result_json); the saved reply, the
8
+ # reply file, the SSE stream and the web bubble keep the model's text.
9
+ #
10
+ # What goes: a heading's, a bullet's and a quote's lead, a table's pipes
11
+ # (a separator row whole), a rule line, ** and __, backticks, a link's URL
12
+ # (its text kept), emoji. What stays: a numbered list's numbers ("1. "),
13
+ # which read well aloud, and a fenced code block's content, byte for byte
14
+ # (its fence lines go; one never closed runs to the end).
15
+ module PlainReply
16
+ # A fence's opening line: its marker (``` or ~~~, three or more). A
17
+ # backtick fence's info string holds no backtick (CommonMark), so a
18
+ # line like "```ls -la``` lists files" is inline code, not a fence.
19
+ FENCE_OPEN = /\A[ \t]*(`{3,}(?=[^`]*\z)|~{3,})/
20
+ HEADING = /^([ \t]*)\#{1,6}[ \t]+/
21
+ BULLET = /^([ \t]*)[-*+][ \t]+/
22
+ QUOTE = /^([ \t]*)(?:>[ \t]?)+/
23
+ RULE = /^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*(\n|\z)/
24
+ TABLE_SEPARATOR = /^[ \t]*\|?[ \t]*:?-{3,}:?[ \t]*(\|[ \t]*:?-{3,}:?[ \t]*)*\|?[ \t]*(\n|\z)/
25
+ TABLE_ROW = /^[ \t]*\|(.*?)\|?[ \t]*$/
26
+ LINK = /\[([^\]\n]+)\]\([^)\s]+(?:[ \t]+"[^"]*")?\)/
27
+ EMPHASIS = /\*\*|__/
28
+ EMOJI = /[ \t]?[\u{1F000}-\u{1FAFF}\u{2600}-\u{27BF}\u{2B00}-\u{2BFF}\u{FE0F}\u{200D}]+/
29
+
30
+ module_function
31
+
32
+ # @param text [String, nil]
33
+ # @return [String, nil] nil for nil
34
+ def strip(text)
35
+ return text if text.nil?
36
+
37
+ lines = segments(text.gsub("\r\n", "\n")).flat_map do |code, body|
38
+ next body if code || body.empty?
39
+
40
+ plain(body.join("\n")).split("\n", -1).map { |line| line.rstrip.sub(/\A[ \t]+/, "") }
41
+ end
42
+ lines = lines.drop_while { |line| line.strip.empty? }
43
+ lines.pop while lines.last&.strip&.empty?
44
+ lines.join("\n")
45
+ end
46
+
47
+ # +text+'s lines as [code?, lines] runs: a fence's content (code) and
48
+ # the text between fences, the fence lines left out.
49
+ # @return [Array<Array(Boolean, Array<String>)>]
50
+ def segments(text)
51
+ runs = [[false, []]]
52
+ close = nil
53
+ text.split("\n", -1).each do |line|
54
+ if close&.match?(line)
55
+ close = nil
56
+ runs << [false, []]
57
+ elsif !close && (open = FENCE_OPEN.match(line))
58
+ close = /\A[ \t]*#{Regexp.escape(open[1][0])}{#{open[1].size},}[ \t]*\z/
59
+ runs << [true, []]
60
+ else
61
+ runs.last.last << line
62
+ end
63
+ end
64
+ runs
65
+ end
66
+
67
+ # A text run made plain (no fence in it).
68
+ def plain(text)
69
+ out = text.gsub(TABLE_SEPARATOR, "").gsub(RULE, "")
70
+ out = out.gsub(TABLE_ROW) { Regexp.last_match(1).split("|").map(&:strip).reject(&:empty?).join(", ") }
71
+ out = out.gsub(HEADING, '\1').gsub(BULLET, '\1').gsub(QUOTE, '\1')
72
+ out.gsub(LINK, '\1').gsub(EMPHASIS, "").delete("`").gsub(EMOJI, "")
73
+ end
74
+ end
75
+ end
@@ -74,6 +74,8 @@ module Samagotchi
74
74
  LAST_SEND = "last-send.json"
75
75
  SKILL_FILE = "chi-peer-SKILL.md"
76
76
  PAIR_PLACEHOLDER = "__CHI_PEER_PAIR__"
77
+ # scripts/pair-remote's path (claude-peer's skill: the SSH pairing).
78
+ PAIR_REMOTE_PLACEHOLDER = "__CHI_PEER_PAIR_REMOTE__"
77
79
  PAYLOADS_PLACEHOLDER = "__CHI_PEER_PAYLOADS__"
78
80
  DIFF_LINES = 20
79
81
  # Under the session's data dir: the moved message went (or was tried).
@@ -261,8 +263,8 @@ module Samagotchi
261
263
  end
262
264
 
263
265
  def send_text(ctx, kind, text)
264
- "#{deliver(ctx, kind: kind, title: text_title(text), text: text, by: "user", salt: command_salt)}; #{self.class::NAME}'s answer comes as the " \
265
- "#{self.class::OUTBOX} context"
266
+ "#{deliver(ctx, kind: kind, title: text_title(text), text: text, by: "user", salt: command_salt)}; #{self.class::NAME}'s answer comes as a " \
267
+ "note with its text (#{self.class::OUTBOX})"
266
268
  rescue SendError => e
267
269
  "#{self.class::COMMAND}: #{e.message}"
268
270
  end
@@ -345,7 +347,10 @@ module Samagotchi
345
347
  "#{peer::NAME} \"pair with chi #{id.to_s[0, 8]}\"."]
346
348
  end
347
349
  lines << "last send: #{last_send_line(ctx)}" if id && last_send(ctx)
348
- lines << "last answer (#{peer::OUTBOX}): #{outbox_line(outbox)}" if outbox
350
+ if outbox
351
+ lines << "last message from #{peer::NAME} (#{peer::OUTBOX}, its text in the conversation): " \
352
+ "#{outbox_line(outbox)}"
353
+ end
349
354
  lines << "skill: **differs from this bundle's**: #{peer::COMMAND} install-skill (Replace), then pair again" if skill_differs?(ctx)
350
355
  lines << transport_line
351
356
  ctx.card(id: peer::STATUS_CARD, title: "#{peer::BUNDLE}: #{paired ? "paired" : "not paired"}",
@@ -401,6 +406,7 @@ module Samagotchi
401
406
  return [target, nil] unless source
402
407
 
403
408
  substitutions = { PAIR_PLACEHOLDER => File.join(File.dirname(source), "pair"),
409
+ PAIR_REMOTE_PLACEHOLDER => File.join(File.dirname(source), "pair-remote"),
404
410
  PAYLOADS_PLACEHOLDER => tilde(ctx.data_dir) }.merge(skill_substitutions(ctx))
405
411
  [target, substitutions.reduce(File.read(source)) { |skill, (placeholder, value)| skill.gsub(placeholder, value) }]
406
412
  end
@@ -462,7 +468,7 @@ module Samagotchi
462
468
  def follow_up(kind)
463
469
  case kind
464
470
  when "context" then "#{self.class::NAME} takes it in; it answers only if something in it is wrong."
465
- else "#{self.class::NAME}'s answer comes as an update of the #{self.class::OUTBOX} context; don't wait or poll."
471
+ else "#{self.class::NAME}'s answer comes as a note with its text (#{self.class::OUTBOX}); don't wait or poll."
466
472
  end
467
473
  end
468
474