samagotchi 0.183.0 → 0.185.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 (151) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +84 -1
  3. data/docs/architecture.md +12 -11
  4. data/docs/bundles.md +63 -36
  5. data/docs/cli.md +10 -1
  6. data/docs/configuration.md +3 -2
  7. data/docs/context.md +76 -10
  8. data/docs/guardrails.md +7 -2
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/block-renderers.md +4 -2
  11. data/docs/internals/bridge.md +7 -3
  12. data/docs/internals/bundles.md +6 -2
  13. data/docs/internals/engine.md +2 -1
  14. data/docs/internals/llm-context-forget.md +6 -0
  15. data/docs/internals/participants.md +5 -2
  16. data/docs/internals/prompt-caching.md +8 -1
  17. data/docs/internals/remote-sessions.md +22 -4
  18. data/docs/internals/session-lifecycle.md +1 -1
  19. data/docs/internals/web-frontend.md +37 -15
  20. data/docs/internals/web-push.md +11 -0
  21. data/docs/internals/working-set.md +238 -6
  22. data/docs/mcp-server.md +11 -3
  23. data/docs/memory.md +2 -1
  24. data/docs/plugins.md +6 -6
  25. data/docs/scheduling.md +19 -0
  26. data/docs/sessions.md +13 -3
  27. data/docs/sub-agent.md +48 -3
  28. data/docs/thin-clients.md +38 -12
  29. data/lib/samagotchi/agent_caller.rb +97 -0
  30. data/lib/samagotchi/bridge.rb +7 -7
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/check.rb +20 -2
  33. data/lib/samagotchi/bundle_manifest.rb +5 -1
  34. data/lib/samagotchi/bundles/claude-peer/manifest.yml +14 -8
  35. data/lib/samagotchi/bundles/claude-peer/plugin.rb +3 -3
  36. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +49 -30
  37. data/lib/samagotchi/bundles/claude-peer/scripts/pair +2 -2
  38. data/lib/samagotchi/bundles/claude-peer/scripts/pair-remote +123 -0
  39. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +11 -3
  40. data/lib/samagotchi/bundles/codex-peer/manifest.yml +10 -8
  41. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  42. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +29 -8
  43. data/lib/samagotchi/bundles/codex-peer/scripts/pair +1 -1
  44. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +11 -3
  45. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  46. data/lib/samagotchi/bundles/mcp/http_client.rb +96 -54
  47. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  48. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  49. data/lib/samagotchi/bundles/system/self_map.md +9 -2
  50. data/lib/samagotchi/client_id.rb +61 -1
  51. data/lib/samagotchi/command_intake.rb +16 -8
  52. data/lib/samagotchi/context_absorber.rb +212 -46
  53. data/lib/samagotchi/delivery.rb +15 -0
  54. data/lib/samagotchi/driver_command.rb +68 -0
  55. data/lib/samagotchi/engine/block_fix.rb +2 -2
  56. data/lib/samagotchi/engine/session.rb +14 -6
  57. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  58. data/lib/samagotchi/engine.rb +13 -5
  59. data/lib/samagotchi/engine_peers.rb +6 -0
  60. data/lib/samagotchi/guardrails/pair_boundary.rb +1 -1
  61. data/lib/samagotchi/mcp_command.rb +7 -2
  62. data/lib/samagotchi/mcp_server/http.rb +3 -3
  63. data/lib/samagotchi/mcp_server/protocol.rb +23 -4
  64. data/lib/samagotchi/mcp_server/stdio.rb +1 -0
  65. data/lib/samagotchi/mcp_server/tools.rb +11 -4
  66. data/lib/samagotchi/model_notes.rb +34 -12
  67. data/lib/samagotchi/objectives_track.rb +2 -1
  68. data/lib/samagotchi/owner_prompt.rb +5 -1
  69. data/lib/samagotchi/parent_report.rb +9 -5
  70. data/lib/samagotchi/plugin/peer.rb +10 -4
  71. data/lib/samagotchi/prompt_files.rb +11 -4
  72. data/lib/samagotchi/prompt_layout.rb +88 -0
  73. data/lib/samagotchi/prompt_part.rb +82 -20
  74. data/lib/samagotchi/reply_wait.rb +16 -4
  75. data/lib/samagotchi/schedule_command.rb +18 -4
  76. data/lib/samagotchi/schedules.rb +49 -14
  77. data/lib/samagotchi/send_command/parent_gate.rb +3 -1
  78. data/lib/samagotchi/send_command.rb +45 -8
  79. data/lib/samagotchi/session.rb +9 -1
  80. data/lib/samagotchi/session_access/ask.rb +58 -14
  81. data/lib/samagotchi/session_access/contract.rb +2 -0
  82. data/lib/samagotchi/session_access/exchange.rb +5 -2
  83. data/lib/samagotchi/session_access/local.rb +13 -3
  84. data/lib/samagotchi/session_access/remote.rb +18 -2
  85. data/lib/samagotchi/session_access.rb +4 -2
  86. data/lib/samagotchi/session_command_catalog.rb +8 -0
  87. data/lib/samagotchi/session_commands.rb +9 -0
  88. data/lib/samagotchi/session_continue.rb +4 -1
  89. data/lib/samagotchi/session_inbox.rb +17 -0
  90. data/lib/samagotchi/session_inbox_delivery.rb +4 -2
  91. data/lib/samagotchi/session_manager/delivery.rb +58 -9
  92. data/lib/samagotchi/session_manager/spawn.rb +7 -1
  93. data/lib/samagotchi/steer.rb +95 -20
  94. data/lib/samagotchi/system_prompt.rb +196 -161
  95. data/lib/samagotchi/terminal_ui/formatting.rb +12 -2
  96. data/lib/samagotchi/tool_activity.rb +4 -0
  97. data/lib/samagotchi/tool_declarations.rb +22 -1
  98. data/lib/samagotchi/tool_names.rb +4 -0
  99. data/lib/samagotchi/toolkit.rb +3 -2
  100. data/lib/samagotchi/tools/ask_session.rb +208 -0
  101. data/lib/samagotchi/tools/builtin_calls.rb +1 -0
  102. data/lib/samagotchi/tools/builtins.rb +5 -0
  103. data/lib/samagotchi/tools/memory.rb +11 -3
  104. data/lib/samagotchi/turn_checkpoint.rb +19 -2
  105. data/lib/samagotchi/turn_stages/context_judge.rb +3 -1
  106. data/lib/samagotchi/turn_stages/objectives.rb +4 -2
  107. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +3 -0
  108. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  109. data/lib/samagotchi/version.rb +1 -1
  110. data/lib/samagotchi/visitor.rb +37 -0
  111. data/lib/samagotchi/web/app.rb +2 -3
  112. data/lib/samagotchi/web/ask_routes.rb +95 -23
  113. data/lib/samagotchi/web/mcp_route.rb +7 -4
  114. data/lib/samagotchi/web/message_display.rb +15 -2
  115. data/lib/samagotchi/web/public/app.js +1 -1
  116. data/lib/samagotchi/web/public/block_fix.js +11 -3
  117. data/lib/samagotchi/web/public/delete_sheet.js +20 -18
  118. data/lib/samagotchi/web/public/history_shape.js +3 -1
  119. data/lib/samagotchi/web/public/index.html +8 -0
  120. data/lib/samagotchi/web/public/peer_links.js +27 -4
  121. data/lib/samagotchi/web/public/peer_note.js +19 -3
  122. data/lib/samagotchi/web/public/peer_text.js +45 -0
  123. data/lib/samagotchi/web/public/picture_regions.js +2 -2
  124. data/lib/samagotchi/web/public/removal_sheet_model.js +3 -4
  125. data/lib/samagotchi/web/public/running_tasks.js +0 -16
  126. data/lib/samagotchi/web/public/session_actions.js +0 -9
  127. data/lib/samagotchi/web/public/turn_events.js +19 -0
  128. data/lib/samagotchi/web/public/working_set_view.js +178 -23
  129. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  130. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  131. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  132. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  133. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  134. data/lib/samagotchi/web/push/notifier.rb +33 -6
  135. data/lib/samagotchi/web/server.rb +1 -1
  136. data/lib/samagotchi/web/session_control.rb +1 -1
  137. data/lib/samagotchi/web/session_create.rb +11 -7
  138. data/lib/samagotchi/web/session_hub.rb +26 -4
  139. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  140. data/lib/samagotchi/worker/command_queue.rb +5 -2
  141. data/lib/samagotchi/worker/senders.rb +79 -0
  142. data/lib/samagotchi/worker.rb +21 -18
  143. data/lib/samagotchi/worker_inbound.rb +12 -4
  144. data/lib/samagotchi/worker_link.rb +2 -2
  145. data/lib/samagotchi/worker_participant_gate.rb +1 -3
  146. data/lib/samagotchi/worker_wakes.rb +12 -0
  147. data/lib/samagotchi/working_set.rb +162 -90
  148. data/lib/samagotchi/working_set_locator.rb +221 -0
  149. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  150. data/lib/samagotchi/working_set_part.rb +281 -0
  151. metadata +13 -1
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "agent_caller"
4
+ require_relative "client_id"
5
+ require_relative "session"
6
+
7
+ module Samagotchi
8
+ # /driver, the agent that drives this session (Session#driver): with no
9
+ # argument, who it is; `/driver NAME` names the agent NAME (agent:NAME),
10
+ # `/driver none` drops it, saved at once. An agent's messages into a
11
+ # session it drives are as chi send's were (no header, never counted
12
+ # toward session.max_wakes); any other agent's are a visitor's (Visitor).
13
+ # Naming one is the user's at a UI (+user_ui+: an attached TUI, the web):
14
+ # from chi send, an agent or anyone else it is refused.
15
+ class DriverCommand
16
+ NAME = "/driver"
17
+ USAGE = "usage: #{NAME} [NAME|none] (NAME: lowercase letters, digits, - and _)".freeze
18
+ REFUSED = "naming this session's driver is the user's: #{NAME} in a chi terminal or the web " \
19
+ "(not chi send or an agent)".freeze
20
+ NONE = "none"
21
+
22
+ # @param engine [Engine] #session
23
+ # @param save [#call] saves the session after a change
24
+ def initialize(engine:, save:)
25
+ @engine = engine
26
+ @save = save
27
+ end
28
+
29
+ # @param args [String] what follows /driver
30
+ # @param user_ui [Boolean] a user at a UI typed it
31
+ # @return [Array(String, Boolean, Symbol)] the reply, whether the
32
+ # driver changed, and :ok or :error
33
+ def run(args, user_ui:)
34
+ session = @engine.session or return [Session::NONE_YET, false, :error]
35
+ words = args.to_s.split
36
+ return [listing(session), false, :ok] if words.empty?
37
+ return [USAGE, false, :error] if words.size > 1
38
+ return [REFUSED, false, :error] unless user_ui
39
+
40
+ driver = driver_for(words.first)
41
+ return [USAGE, false, :error] if driver == :invalid
42
+ return ["#{listing(session)}\n(no change)", false, :ok] if driver == session.driver
43
+
44
+ session.driver = driver
45
+ @save.call(session)
46
+ [listing(session), true, :ok]
47
+ end
48
+
49
+ private
50
+
51
+ # nil for none, agent:<name> for a name, :invalid for anything else.
52
+ def driver_for(word)
53
+ return nil if word.downcase == NONE
54
+
55
+ name = AgentCaller.clean(word)
56
+ name ? ClientId.agent(name) : :invalid
57
+ end
58
+
59
+ # "driver: agent claude (its messages are as yours: no header, not
60
+ # counted)" or "driver: none (every agent here is a visitor)".
61
+ def listing(session)
62
+ name = ClientId.agent_name(session.driver)
63
+ return "driver: none (every agent's message here is a visitor's: one header line, counted toward session.max_wakes)" unless name
64
+
65
+ "driver: agent #{name} (its messages go in as yours: no header line, not counted toward session.max_wakes)"
66
+ end
67
+ end
68
+ end
@@ -72,7 +72,7 @@ module Samagotchi
72
72
  # is that answer's own ask (its result lands in it, its event names it).
73
73
  asking = [index, key]
74
74
  @block_fix_mutex.synchronize do
75
- return [202, { state: "running" }] if block_fix_pending?(asking)
75
+ return [202, { state: "running", key: key }] if block_fix_pending?(asking)
76
76
  return block_fix_refused(429, :fix_limit) if block_fix_asked(answer, index) >= BlockFix::PER_ANSWER
77
77
  return block_fix_refused(429, :fix_busy) if @block_fix_running.size >= BlockFix::MAX_RUNNING
78
78
 
@@ -83,7 +83,7 @@ module Samagotchi
83
83
  Log.info(:model, "block_fix_asked", lang: lang, key: key, bytes: source.to_s.bytesize)
84
84
  start_block_fix(conversation, turn_id: turn_id.to_s, lang: lang.to_s, key: key, source: source.to_s,
85
85
  reason: reason.to_s, anchor: anchor)
86
- [202, { state: "running" }]
86
+ [202, { state: "running", key: key }]
87
87
  end
88
88
 
89
89
  # The results waiting, applied: on the worker's loop, between turns
@@ -77,18 +77,26 @@ module Samagotchi
77
77
  # a level change builds it again. A build that
78
78
  # misses the cache names the model and the level through its own
79
79
  # lambdas (#model_identity, #turn_thinking), which resolve again.
80
- def system_prompt(model = nil)
80
+ # +record+: false builds without recording (the turn-end warm-up's
81
+ # prompt, which nothing sends as the session's: the session keeps the
82
+ # parts, notes and memory index of the prompt its turn sent).
83
+ def system_prompt(model = nil, record: true)
81
84
  model ||= effective_model
82
85
  chat = model.chat?
83
86
  level = chat ? nil : @model_settings.thinking_level(model)
84
- prompt = @prompt_builder.build(chat: chat, thinking: level, layers: model.llm_context_layers(@model_settings.llm_context_session_args))
87
+ # One Built: a #reset! on another thread right after the build leaves it whole.
88
+ built = @prompt_builder.built_for(chat: chat, thinking: level,
89
+ layers: model.llm_context_layers(@model_settings.llm_context_session_args),
90
+ record: record)
91
+ return built.prompt unless record
92
+
85
93
  # The memory indexes this prompt holds: /stats, the snapshot, analytics.json.
86
- @metrics.memory_index = @prompt_builder.memory_index
94
+ @metrics.memory_index = built.memory_index
87
95
  # The model notes it carries: the session records them (/stats, /model, the web).
88
- record_prompt_notes(@prompt_builder.prompt_notes)
96
+ record_prompt_notes(built.notes)
89
97
  # And the sizes of its parts (PromptPart), for the web's head view.
90
- record_prompt_parts(@prompt_builder.prompt_parts)
91
- prompt
98
+ record_prompt_parts(built.prompt_parts)
99
+ built.prompt
92
100
  end
93
101
 
94
102
  # The base prompt (specs, plugins' declarations).
@@ -49,12 +49,13 @@ module Samagotchi
49
49
 
50
50
  # The stage over the kernel and the Engine's PromptWarmup (built in
51
51
  # #initialize, once the kernel and the reminder queue are). Its one
52
- # callable is the system prompt, built late (side effects); the
53
- # host's probe goes with each call (#next_turn_waiting, set after).
52
+ # callable is the system prompt, built late and not recorded (the
53
+ # session keeps the parts its turn sent); the host's probe goes with
54
+ # each call (#next_turn_waiting, set after).
54
55
  def build_turn_warmup
55
56
  TurnStages::Warmup.new(prompt_warmup: @prompt_warmup, kernel: @kernel, turn_state: @turn_state,
56
57
  model_settings: @model_settings, reminder_queue: @reminder_queue,
57
- system_prompt: ->(model) { system_prompt(model) })
58
+ system_prompt: ->(model) { system_prompt(model, record: false) })
58
59
  end
59
60
  private :build_turn_warmup
60
61
 
@@ -423,9 +423,10 @@ module Samagotchi
423
423
  # The tools a scratch session doesn't offer, and its memory_write.
424
424
  def restrict_scratch_tools!
425
425
  # 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) }
426
+ # note it left in a peer or a question's turn; its memories would too
427
+ # (write and edit into the memories: ScratchWrites).
428
+ [Tools::Delegate::NAME, Tools::DelegateResult::NAME, Tools::SendNote::NAME,
429
+ Tools::AskSession::NAME].each { |name| @tools.unregister(name) }
429
430
  @tools[Tools::MemoryWrite::NAME].handler = ->(_call, _kctx) { SCRATCH_MEMORY_WRITE }
430
431
  end
431
432
  private :restrict_scratch_tools!
@@ -857,8 +858,11 @@ module Samagotchi
857
858
  # +history_size+: turn.messages' size under the system head, before
858
859
  # the reminders and the prompt (#turn_messages): where the turn's own
859
860
  # messages start in what it keeps (the end event's kept_from).
861
+ # +opener_source+: the sender its prompt is saved with (the opener's
862
+ # source, Steer::OPENER_HEADERS), nil for the owner's (no source).
860
863
  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
864
+ :limit, :resumed, :resume_from, :wall, :verify, :revises, :outcome, :history_size,
865
+ :opener_source) do
862
866
  # The turn's id (:turn_started's turn_id, its metrics record's id and
863
867
  # its saved prompt's), session, origin and controller: its context's.
864
868
  def id = context.id
@@ -949,10 +953,11 @@ module Samagotchi
949
953
  # one-line summary:.
950
954
  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
955
  origin: TurnOrigin::NONE, images: [], id: nil, resumed: false, resume_from: nil, verify: nil, revises: nil,
952
- input_waiting: nil)
956
+ input_waiting: nil, opener_source: nil)
953
957
  turn = begin_turn(session, prompt, on_event: on_event, cancel_controller: cancel_controller, origin: origin,
954
958
  continue: continue, id: id, verify: verify, revises: revises,
955
959
  input_waiting: input_waiting)
960
+ turn.opener_source = opener_source.to_s unless opener_source.to_s.empty?
956
961
  if continue
957
962
  turn.resumed = resumed
958
963
  turn.resume_from = resume_from
@@ -1204,6 +1209,9 @@ module Samagotchi
1204
1209
  **participant_mode_fields(turn.context), MessageTime::KEY => turn.at }
1205
1210
  user_message[:verify] = turn.verify.to_h if turn.verify
1206
1211
  user_message[:images] = image_refs unless image_refs.empty?
1212
+ # Only an opener from a sender the model reads a header for
1213
+ # (Steer::OPENER_HEADERS): the owner's keeps its bytes.
1214
+ user_message[:source] = turn.opener_source if turn.opener_source
1207
1215
  turn.messages << user_message
1208
1216
  session.last_prompt = turn.prompt
1209
1217
  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
@@ -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
@@ -59,7 +59,7 @@ module Samagotchi
59
59
 
60
60
  def header_refusal(env, message)
61
61
  params = message["params"].is_a?(Hash) ? message["params"] : {}
62
- id = message["id"]
62
+ id = Protocol.request_id(message)
63
63
  version = env["HTTP_MCP_PROTOCOL_VERSION"]
64
64
  meta_version = params.dig("_meta", VERSION_META)
65
65
  unless version == meta_version
@@ -86,13 +86,13 @@ module Samagotchi
86
86
 
87
87
  session = env["HTTP_MCP_SESSION_ID"]
88
88
  unless session.is_a?(String) && SESSION_ID.match?(session)
89
- return Protocol.error_body(message["id"], Protocol::INVALID_REQUEST, "Bad Request: Missing session ID")
89
+ return Protocol.error_body(Protocol.request_id(message), Protocol::INVALID_REQUEST, "Bad Request: Missing session ID")
90
90
  end
91
91
 
92
92
  version = env["HTTP_MCP_PROTOCOL_VERSION"]
93
93
  return nil if version.nil? || LEGACY_VERSIONS.include?(version)
94
94
 
95
- Protocol.error_body(message["id"], Protocol::INVALID_REQUEST,
95
+ Protocol.error_body(Protocol.request_id(message), Protocol::INVALID_REQUEST,
96
96
  "Bad Request: Unsupported protocol version #{version} (supported: #{LEGACY_VERSIONS.join(", ")})")
97
97
  end
98
98
 
@@ -130,6 +130,18 @@ module Samagotchi
130
130
  { jsonrpc: "2.0", id: id, error: error }
131
131
  end
132
132
 
133
+ def self.valid_id?(message)
134
+ return false unless message.is_a?(Hash)
135
+ return true unless message.key?("id")
136
+
137
+ id = message["id"]
138
+ id.is_a?(String) || id.nil? || id.is_a?(Integer) || (id.is_a?(Float) && id.finite?)
139
+ end
140
+
141
+ def self.request_id(message)
142
+ valid_id?(message) && message.key?("id") ? message["id"] : nil
143
+ end
144
+
133
145
  # @param tools [#list, #call]
134
146
  # @param instructions [String, nil] what the server says it is
135
147
  # @param name [String] serverInfo's name
@@ -156,17 +168,24 @@ module Samagotchi
156
168
  def handle(message, era: nil)
157
169
  era ||= self.class.era_of(message)
158
170
  unless message.is_a?(Hash) && message["jsonrpc"] == "2.0"
159
- return error(message.is_a?(Hash) ? message["id"] : nil, INVALID_REQUEST, "Invalid Request", era)
171
+ return error(self.class.request_id(message), INVALID_REQUEST, "Invalid Request", era)
172
+ end
173
+ return nil if message.key?("result") || message.key?("error")
174
+ unless message.key?("method")
175
+ return error(self.class.request_id(message), INVALID_REQUEST, "Invalid Request", era)
160
176
  end
161
- return nil unless message.key?("id") && message.key?("method")
177
+ return nil unless message.key?("id")
162
178
 
163
- id = message["id"]
179
+ id = self.class.request_id(message)
164
180
  method = message["method"]
165
181
  params = message.fetch("params", {})
166
182
  return error(id, INVALID_REQUEST, "Invalid Request", era) unless method.is_a?(String) && params.is_a?(Hash)
167
183
  if params.key?("_meta") && !params["_meta"].is_a?(Hash)
168
184
  return error(id, INVALID_REQUEST, "Invalid Request: params._meta is an object", era)
169
185
  end
186
+ unless self.class.valid_id?(message)
187
+ return error(nil, INVALID_REQUEST, "Invalid Request: id is a string, a number or null", era)
188
+ end
170
189
 
171
190
  # A modern connection's initialize is -32601 whatever it names.
172
191
  if era == :modern && method != "initialize" && (refused = version_refusal(id, params))
@@ -175,7 +194,7 @@ module Samagotchi
175
194
 
176
195
  dispatch(id, method, params, era)
177
196
  rescue StandardError => e
178
- error(message.is_a?(Hash) ? message["id"] : nil, INTERNAL_ERROR, "Internal error: #{e.message}", era)
197
+ error(self.class.request_id(message), INTERNAL_ERROR, "Internal error: #{e.message}", era)
179
198
  end
180
199
 
181
200
  private
@@ -61,6 +61,7 @@ module Samagotchi
61
61
 
62
62
  def lock_era(message)
63
63
  return if @era || !message.is_a?(Hash) || !message.key?("id") || !message["method"].is_a?(String)
64
+ return unless Protocol.valid_id?(message)
64
65
 
65
66
  @era = Protocol.era_of(message)
66
67
  @log&.call("mcp: #{@era} era (#{message["method"]})")
@@ -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,8 +23,11 @@ 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
- # (Web::AskRoutes::ASK_MAX_SECONDS).
29
+ # (Web::AskRoutes::ASK_MAX_SECONDS); under --remote about a minute for
30
+ # a slow worker (the other chi web's routes make their own tries).
27
31
  CAP = 35
28
32
  LIST_LIMIT = 20
29
33
  LIST_MAX = 50
@@ -72,8 +76,11 @@ module Samagotchi
72
76
  # @param cap [Numeric] seconds a chi_ask or chi_answer takes in all (CAP)
73
77
  # @param exchange [#call, nil] (access) -> the Exchange a call uses
74
78
  # (chi web's carries its stop check); nil: a plain one
75
- 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)
76
82
  @access = access
83
+ @agent = agent
77
84
  @slice = slice
78
85
  @cap = cap
79
86
  @exchange = exchange || ->(backend) { SessionAccess::Exchange.new(backend) }
@@ -168,9 +175,9 @@ module Samagotchi
168
175
  # parent_answers of the session asked and its chain's newest link; on
169
176
  # a remote chi web's turn route gates the same ids itself.
170
177
  def sender(asker, given, prompt)
171
- 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?
172
179
 
173
- asker.agent_line(prompt, session: targets(given))
180
+ asker.agent_line(prompt, session: targets(given), name: @agent)
174
181
  end
175
182
 
176
183
  def targets(given)
@@ -120,29 +120,51 @@ module Samagotchi
120
120
  return nil unless entries
121
121
  return nil unless ModelMatch.match?(entries, name: name, key: key, small: small)
122
122
 
123
- body = File.read(path, encoding: "UTF-8").sub(/\A[^\n]*\n?/, "").strip
124
- return nil if body.empty?
125
-
126
- body = with_overlay(body, stem, scope, [key, fallback_key], env: env)
123
+ body = body_at(path, [key, fallback_key], dir: Tools::MemoryRead.memories_dir(scope, env: env))
124
+ return nil unless body
127
125
 
128
126
  Note.new(name: stem, scope: scope, body: body, chars: body.length, digest: Digest::SHA256.hexdigest(body)[0, 12])
129
127
  rescue StandardError
130
128
  nil
131
129
  end
132
130
 
131
+ # A note's body as the prompt carries it: the file at +path+ without
132
+ # its models: line, stripped, its model overlay in +dir+ (the note's
133
+ # scope's folder) appended (#with_overlay) for the first of +keys+ that
134
+ # has one; nil when the body is empty. The prompt's build (#for) and the
135
+ # working set's re-fetch of a note part (with the saved keys and dir).
136
+ def body_at(path, keys, dir:)
137
+ body = File.read(path, encoding: "UTF-8").sub(/\A[^\n]*\n?/, "").strip
138
+ return nil if body.empty?
139
+
140
+ with_overlay(body, File.basename(path, ".md"), keys, dir: dir)
141
+ end
142
+
133
143
  # The note's model overlay appended as memory_read appends one: the
134
144
  # key's, else the fallback key's. The file is read by its own path, not
135
- # by name through memory_read (whose names are comma lists). +env+: the
136
- # XDG env the scope's dir (and so the overlay) resolves from.
137
- def with_overlay(body, stem, scope, keys, env: ENV)
145
+ # by name through memory_read (whose names are comma lists). +dir+: the
146
+ # scope's folder the overlay sits in.
147
+ def with_overlay(body, stem, keys, dir:)
148
+ overlay, overlay_key = overlay_path(stem, keys, dir: dir)
149
+ return body unless overlay
150
+
151
+ # The key as given in the label (prompt bytes), stripped in the path.
152
+ "#{body}#{Tools::MemoryRead::SEPARATOR}Model-specific guidance (#{overlay_key}):\n" \
153
+ "#{File.read(overlay, encoding: "UTF-8").strip}"
154
+ end
155
+
156
+ # The note +stem+'s model overlay file in +dir+ for the first of +keys+
157
+ # that has one: [path, the key as given (unstripped)], or nil. The
158
+ # build (#with_overlay) and the working set's files of a note part
159
+ # (WorkingSet::Locator#composed).
160
+ def overlay_path(stem, keys, dir:)
138
161
  keys.compact.each do |overlay_key|
139
- overlay = ModelOverlay.overlay_path_for(stem, overlay_key, scope, env: env)
140
- next unless overlay && File.file?(overlay)
162
+ next if overlay_key.to_s.strip.empty?
141
163
 
142
- return "#{body}#{Tools::MemoryRead::SEPARATOR}Model-specific guidance (#{overlay_key}):\n" \
143
- "#{File.read(overlay, encoding: "UTF-8").strip}"
164
+ overlay = File.join(dir, "#{stem}.#{overlay_key.to_s.strip}.md")
165
+ return [overlay, overlay_key] if File.file?(overlay)
144
166
  end
145
- body
167
+ nil
146
168
  end
147
169
 
148
170
  # A model overlay of a note (`model_notes_a.<key>.md`) is read with
@@ -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)
@@ -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
 
@@ -117,11 +117,18 @@ module Samagotchi
117
117
  # the file is empty or can't be read.
118
118
  # @return [String, nil]
119
119
  def section(path, header)
120
- content = File.read(path, encoding: "UTF-8").strip
121
- return nil if content.empty?
120
+ content = content(path)
121
+ content && "#{header}\n#{content}"
122
+ end
122
123
 
123
- "#{header}\n#{content}"
124
- rescue StandardError
124
+ # +path+'s text as the prompt carries it under its header: stripped;
125
+ # nil when empty or unreadable. The prompt's build (#section) and the
126
+ # working set's re-fetch of an AGENTS.md part.
127
+ # @return [String, nil]
128
+ def content(path)
129
+ content = File.read(path, encoding: "UTF-8").strip
130
+ content.empty? ? nil : content
131
+ rescue StandardError # degrade-ok: an unreadable file is left out of the prompt, as before
125
132
  nil
126
133
  end
127
134
  end