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,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "prompt_part"
4
+
5
+ module Samagotchi
6
+ # Where each SystemPrompt::Item of a build sits in the prompt the build
7
+ # made, worked out once beside it (SystemPrompt#prompt_parts_for): the
8
+ # place fields of its PromptPart (at, len, lead, digest, head). The
9
+ # sections are joined by "\n" (the stable ones, then the volatile ones),
10
+ # each section's items by its join; joins and the scope headings that
11
+ # belong to no item fall outside every span (a note's heading is the
12
+ # first note's lead). See docs/internals/working-set.md (Prompt parts as
13
+ # sent).
14
+ #
15
+ # The tool declarations: on a chat host they are not in the prompt (no
16
+ # place); native, inside the base text ("You have access to the following
17
+ # tools:"), whose own slice leaves them out, or, on Gemma, after the last
18
+ # section, where the prompt was rstripped before them: an item running
19
+ # into that strip is cut at it.
20
+ class PromptLayout
21
+ # What the base text says before the declarations: SystemPrompt#assist_system_prompt
22
+ # writes it from here, so the two can't drift.
23
+ TOOLS_LEAD = "You have access to the following tools:\n\n"
24
+
25
+ # @param prompt [String] the built prompt
26
+ # @param sections [Array<SystemPrompt::Section>] in prompt order
27
+ # @param declarations [String, nil] the native declarations text (nil: chat)
28
+ # @param tail [Boolean] Gemma's: the declarations follow the rstripped prompt
29
+ def initialize(prompt, sections, declarations:, tail:)
30
+ @head = PromptPart.digest_of(prompt, 16)
31
+ @spans = {}.compare_by_identity
32
+ @end = tail && declarations ? prompt.length - declarations.length : prompt.length
33
+ at = 0
34
+ sections.each do |section|
35
+ offset = at
36
+ section.items.each do |item|
37
+ @spans[item] = [offset, item.sent.length.clamp(0, [@end - offset, 0].max)]
38
+ offset += item.sent.length + section.join.length
39
+ end
40
+ at += section.text.length + 1
41
+ end
42
+ @tools = tools_span(sections, declarations, tail)
43
+ end
44
+
45
+ # Whether the declarations sit inside the base text (their chars move
46
+ # out of the base part, SystemPrompt#prompt_parts_for).
47
+ def tools_in_base? = !@tools.nil? && !@tools_tail
48
+
49
+ # The place fields of +item+'s part.
50
+ # @return [Hash]
51
+ def place(item)
52
+ at, len = @spans.fetch(item)
53
+ body = item.text
54
+ if item.kind == :base && tools_in_base?
55
+ from = @tools[0] - at - item.lead.length
56
+ body = body[0, from].to_s + body[(from + @tools[1])..].to_s
57
+ end
58
+ { at: at, len: len, lead: item.lead.length, digest: PromptPart.digest_of(body), head: @head }
59
+ end
60
+
61
+ # The tools part's place fields: none on a chat host.
62
+ # @return [Hash]
63
+ def tools_place
64
+ return {} unless @tools
65
+
66
+ { at: @tools[0], len: @tools[1], lead: 0, head: @head }
67
+ end
68
+
69
+ private
70
+
71
+ # [at, len] of the declarations in the prompt, nil when they aren't in
72
+ # it (chat) or can't be found.
73
+ def tools_span(sections, declarations, tail)
74
+ return nil unless declarations
75
+
76
+ if tail
77
+ @tools_tail = true
78
+ return [@end, declarations.length]
79
+ end
80
+
81
+ base = sections.first&.items&.first
82
+ return nil unless base&.kind == :base
83
+
84
+ index = base.text.index("#{TOOLS_LEAD}#{declarations}")
85
+ index && [@spans.fetch(base)[0] + base.lead.length + index + TOOLS_LEAD.length, declarations.length]
86
+ end
87
+ end
88
+ end
@@ -1,34 +1,64 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "digest"
3
4
  require_relative "token_usage"
4
5
 
5
6
  module Samagotchi
6
- # One part of a session's system prompt, as its size: what the session
7
- # file's `prompt_parts` records at each prompt build and the web's head view
8
- # draws (the text itself is not kept). kind: a SystemPrompt::KINDS word, or
9
- # "tools" (the tool declarations, wherever the model gets them); label: what
10
- # the row says ("AGENTS.md", "N declared"); chars: the part's length in the
11
- # prompt (a multi-item section's headings and joins are in its first part,
12
- # so a section's parts sum to its text); tokens: chars at TokenUsage's one
13
- # ratio; ref: the bare memory name (identity, notes, preloads), the file
14
- # path (agents, appended), "bundle/name" (plugins), the scope (indexes),
15
- # else nil; scope: a memory part's scope, "project" or "system" (identity:
16
- # system; a note: its own; a preload: the scope that answered), so the
17
- # page tells a project x from a system x; nil for other kinds and in a
18
- # file written before it (the page then matches by name alone).
19
- PromptPart = Data.define(:kind, :label, :chars, :tokens, :ref, :scope) do
20
- def initialize(kind:, label:, chars:, tokens:, ref: nil, scope: nil)
7
+ # One part of a session's system prompt, as its size and its place: what
8
+ # the session file's `prompt_parts` records at each prompt build and the
9
+ # web's head view draws (the text itself is not kept: the sent prompt is,
10
+ # as the session's messages[0]). kind: a SystemPrompt::KINDS word, or
11
+ # "tools" (the tool declarations, wherever the model gets them); label:
12
+ # what the row says ("AGENTS.md", "N declared"); chars: the part's length
13
+ # in the prompt (a multi-item section's headings and joins are in its
14
+ # first part, so a section's parts sum to its text); tokens: chars at
15
+ # TokenUsage's one ratio; ref: the bare memory name (identity, notes,
16
+ # preloads), the file path (agents, appended), "bundle/name" (plugins),
17
+ # the scope (indexes), else nil; scope: a memory part's scope, "project"
18
+ # or "system" (identity: system; a note: its own; a preload: the scope
19
+ # that answered), so the page tells a project x from a system x; nil for
20
+ # other kinds and in a file written before it (the page then matches by
21
+ # name alone).
22
+ #
23
+ # Where it sits in the prompt the build made (docs/internals/working-set.md,
24
+ # Prompt parts as sent), each nil in a file an older chi wrote and left
25
+ # out of #to_h when nil, as scope is:
26
+ # at: the offset its lead starts at; len: its length, lead included (NOT
27
+ # chars: a section's first part is charged its joins); lead: the lead's
28
+ # length (what chi adds before the item's own text: the "System identity
29
+ # …:" line, a note's "## name", a file's header), so the sent slice is
30
+ # head[at, len] and the item's own text head[at + lead, len - lead]. The
31
+ # tools part has one only where the declarations are in the prompt
32
+ # (native: inside the base text, whose slice leaves them out, or Gemma's
33
+ # tail); on a chat host they are a request field. digest: 12 hex of
34
+ # SHA-256 over the item's own text (as PromptNote's); head: 16 hex of
35
+ # SHA-256 of the whole built prompt, the same on every part of a build,
36
+ # so a reader knows whether a saved head is the one the parts were built
37
+ # with. params: how to fetch the item again (string keys): a memory's
38
+ # requested_scope, model_key, fallback_model_key, project_dir,
39
+ # system_dir; a file's path; the tools' [{name, chars}] (chars only where
40
+ # the renderer gives one per tool).
41
+ PromptPart = Data.define(:kind, :label, :chars, :tokens, :ref, :scope, :at, :len, :lead, :digest, :head, :params) do
42
+ def initialize(kind:, label:, chars:, tokens:, ref: nil, scope: nil, at: nil, len: nil, lead: nil, digest: nil, head: nil,
43
+ params: nil)
21
44
  super
22
45
  end
23
46
 
47
+ # The fields that say where a part sits (left out of #to_h when nil).
48
+ PLACE = %i[at len lead digest head params].freeze
49
+
24
50
  # A part of +chars+ characters, its tokens counted by the one ratio.
25
- def self.build(kind:, label:, chars:, ref: nil, scope: nil)
26
- new(kind: kind.to_s, label: label.to_s, chars: chars, tokens: tokens_for(chars), ref: ref&.to_s, scope: scope&.to_s)
51
+ def self.build(kind:, label:, chars:, ref: nil, scope: nil, **place)
52
+ new(kind: kind.to_s, label: label.to_s, chars: chars, tokens: tokens_for(chars), ref: ref&.to_s, scope: scope&.to_s,
53
+ **place.slice(*PLACE))
27
54
  end
28
55
 
29
56
  # @return [Integer] the tokens +chars+ characters count as
30
57
  def self.tokens_for(chars) = (chars / TokenUsage::CHARS_PER_TOKEN).ceil
31
58
 
59
+ # The short digests: an item's text (12 hex), the whole prompt (16).
60
+ def self.digest_of(text, size = 12) = Digest::SHA256.hexdigest(text.to_s)[0, size]
61
+
32
62
  # A saved or wire record (string or symbol keys); nil without a kind.
33
63
  def self.from_h(raw)
34
64
  return raw if raw.is_a?(PromptPart)
@@ -41,9 +71,22 @@ module Samagotchi
41
71
  chars = get.call(:chars)
42
72
  chars = chars.is_a?(Numeric) ? chars.to_i : 0
43
73
  tokens = get.call(:tokens)
74
+ int = ->(key) { get.call(key).is_a?(Integer) ? get.call(key) : nil }
75
+ text = ->(key) { get.call(key).is_a?(String) ? get.call(key) : nil }
76
+ params = get.call(:params)
44
77
  new(kind: kind, label: get.call(:label).to_s, chars: chars,
45
78
  tokens: tokens.is_a?(Numeric) ? tokens.to_i : tokens_for(chars), ref: get.call(:ref)&.to_s,
46
- scope: get.call(:scope)&.to_s)
79
+ scope: get.call(:scope)&.to_s, at: int.call(:at), len: int.call(:len), lead: int.call(:lead),
80
+ digest: text.call(:digest), head: text.call(:head), params: params.is_a?(Hash) ? stringified(params) : nil)
81
+ end
82
+
83
+ # +value+ with string keys all the way down (params as a file reads them).
84
+ def self.stringified(value)
85
+ case value
86
+ when Hash then value.to_h { |key, inner| [key.to_s, stringified(inner)] }
87
+ when Array then value.map { |inner| stringified(inner) }
88
+ else value
89
+ end
47
90
  end
48
91
 
49
92
  # The records of a saved list (others dropped).
@@ -52,11 +95,30 @@ module Samagotchi
52
95
  Array(raw).filter_map { |entry| from_h(entry) }
53
96
  end
54
97
 
55
- # The record (the wire's, the file's): without scope when it has none,
56
- # so a part that has no scope reads as an older chi wrote it.
98
+ # Each part's key, from the parts list alone (chi web's route takes it,
99
+ # the page's ws_sections.js startRows has the twin): "kind:ref" (the
100
+ # label without a ref), "@scope" when it has one, "#n" for the nth
101
+ # repeat of that in parts order (a duplicate preload: "preloads:x#2").
102
+ # spec/shared/prompt_part_keys.json holds both sides to one list.
103
+ # @param parts [Array<PromptPart, Hash>]
104
+ # @return [Array<String>]
105
+ def self.keys(parts)
106
+ seen = Hash.new(0)
107
+ list(parts).map do |part|
108
+ key = "#{part.kind}:#{part.ref || part.label}"
109
+ key = "#{key}@#{part.scope}" if part.scope
110
+ seen[key] += 1
111
+ seen[key] == 1 ? key : "#{key}##{seen[key]}"
112
+ end
113
+ end
114
+
115
+ # The record (the wire's, the file's): without scope and the place
116
+ # fields when it has none, so a part that has none reads as an older
117
+ # chi wrote it.
57
118
  def to_h
58
119
  hash = super
59
120
  hash.delete(:scope) if scope.nil?
121
+ PLACE.each { |key| hash.delete(key) if hash[key].nil? }
60
122
  hash
61
123
  end
62
124
 
@@ -196,16 +196,28 @@ module Samagotchi
196
196
  end
197
197
 
198
198
  # Whether +turn+ is a turn the caller can wait for: running now, queued
199
- # as its own turn, the last one to have ended, or an input a turn's
200
- # drain merged (its merge record: the wait follows it to that turn).
199
+ # as its own turn, the last one to have ended, one that ended with its
200
+ # reply file (SessionInbox.input_taken?'s evidence) or was settled, or
201
+ # an input a turn's drain merged (its merge record: the wait follows it
202
+ # to that turn).
201
203
  def known_turn?(session, session_dir:, turn:)
202
204
  id = turn.to_s
203
205
  return false if id.empty?
204
206
 
205
207
  running = session.status == Session::STATUS_RUNNING && session.interrupted_turn&.enqueued_id == id
206
208
  queued = SessionInbox.waiting_input(session_dir, id) == :turn_end
207
- ended = session.last_turn&.enqueued_id == id || !TurnCheckpoint.settled_turn(session_dir, id).nil?
208
- running || queued || ended || !SessionInbox.merged_into(session_dir, id).nil?
209
+ running || queued || ended_turn?(session, session_dir: session_dir, turn: id) ||
210
+ !SessionInbox.merged_into(session_dir, id).nil?
211
+ end
212
+
213
+ # Whether +turn+ has ended: the last one to have ended, one with its
214
+ # reply file, or one settled (refused, canceled, killed).
215
+ def ended_turn?(session, session_dir:, turn:)
216
+ id = turn.to_s
217
+ return false if id.empty?
218
+
219
+ session.last_turn&.enqueued_id == id || !SessionInbox.reply_for(session_dir, id).nil? ||
220
+ !TurnCheckpoint.settled_turn(session_dir, id).nil?
209
221
  end
210
222
 
211
223
  # Whether the session's live worker names TURN_IDS_FEATURE.
@@ -186,7 +186,11 @@ module Samagotchi
186
186
 
187
187
  result = @schedules.tick(dry_run: @opts[:dry_run] ? true : false)
188
188
  if @opts[:format] == "json"
189
- @stdout.puts(JSON.pretty_generate({ "locked" => result.locked, "outcomes" => result.outcomes.map { |outcome| { "id" => outcome.id, "status" => outcome.status, "detail" => outcome.detail } } }))
189
+ outcomes = result.outcomes.map do |outcome|
190
+ line = { "id" => outcome.id, "status" => outcome.status, "detail" => outcome.detail }
191
+ outcome.disabled ? line.merge("disabled" => true) : line
192
+ end
193
+ @stdout.puts(JSON.pretty_generate({ "locked" => result.locked, "outcomes" => outcomes }))
190
194
  return CLI::Exit::OK
191
195
  end
192
196
 
@@ -201,7 +205,7 @@ module Samagotchi
201
205
 
202
206
  result.outcomes.each do |outcome|
203
207
  word = outcome.status == "dry" ? "would fire" : outcome.status
204
- @stdout.puts("#{outcome.id} #{word} #{outcome.detail}")
208
+ @stdout.puts("#{outcome.id} #{word} #{outcome.detail}#{" (disabled)" if outcome.disabled}")
205
209
  end
206
210
  CLI::Exit::OK
207
211
  rescue Schedules::Corrupt => e
@@ -216,7 +220,7 @@ module Samagotchi
216
220
  return failed("no schedule #{id}") if result.nil?
217
221
 
218
222
  if result.is_a?(Schedules::Outcome)
219
- @stdout.puts("#{id}: #{result.status} · #{result.detail}")
223
+ @stdout.puts("#{id}: #{result.status} · #{result.detail}#{" (disabled)" if result.disabled}")
220
224
  return result.status == "failed" ? CLI::Exit::FAILED : CLI::Exit::OK
221
225
  end
222
226
 
@@ -242,7 +246,17 @@ module Samagotchi
242
246
  def entry_line(entry)
243
247
  note = ""
244
248
  note += " skips #{entry.skips} of #{entry.max_skips} (#{skip_window(entry)})" if entry.skips.positive?
245
- note += " disabled after #{entry.failures} failures" unless entry.enabled
249
+ unless entry.enabled
250
+ note += if entry.last_result == "disabled"
251
+ " disabled"
252
+ elsif entry.skips >= entry.max_skips
253
+ " disabled after #{entry.skips} #{entry.skips == 1 ? "skip" : "skips"}"
254
+ elsif entry.failures >= entry.max_failures
255
+ " disabled after #{entry.failures} #{entry.failures == 1 ? "failure" : "failures"}"
256
+ else
257
+ " disabled"
258
+ end
259
+ end
246
260
  note += " last: #{entry.last_result}" if entry.last_result
247
261
  "#{entry.id} #{entry.mode} #{entry.recurrence_words} #{clock(entry.next_due)} #{entry.head[0, 8]}#{note}"
248
262
  end
@@ -163,9 +163,10 @@ module Samagotchi
163
163
  )
164
164
 
165
165
  # What one entry did in a tick: "fired", "skipped", "missed", "failed" or
166
- # "dry" (a --dry-run's "would fire"). +detail+ is the reason.
167
- Outcome = Data.define(:id, :title, :status, :detail, :entry) do
168
- def initialize(id:, status:, title: nil, detail: nil, entry: nil) = super
166
+ # "dry" (a --dry-run's "would fire"). +detail+ is the reason. +disabled+:
167
+ # this skip or failure used up a recurring entry's budget (#mark_disabled).
168
+ Outcome = Data.define(:id, :title, :status, :detail, :entry, :disabled, :session_id) do
169
+ def initialize(id:, status:, title: nil, detail: nil, entry: nil, disabled: false, session_id: nil) = super
169
170
  end
170
171
 
171
172
  # A whole tick.
@@ -348,6 +349,7 @@ module Samagotchi
348
349
  pending = []
349
350
  prune_after = []
350
351
  links = nil
352
+ started = []
351
353
 
352
354
  FileUtils.mkdir_p(@store_dir)
353
355
  FileUtils.mkdir_p(@state_dir)
@@ -359,7 +361,7 @@ module Samagotchi
359
361
  end
360
362
 
361
363
  file = read(strict: true)
362
- list = file.entries.grep(Entry)
364
+ list = started = file.entries.grep(Entry)
363
365
  # Ordered by the moment each entry is due, then id: with one chain
364
366
  # firing per tick, the entries of that chain take turns (a skipped
365
367
  # entry keeps its `next_due`, so the earliest waiting one goes next).
@@ -465,7 +467,7 @@ module Samagotchi
465
467
  end
466
468
  links ||= links_now unless prune_after.empty?
467
469
  prune_after.each { |entry| prune(entry, links) }
468
- Tick.new(locked: false, outcomes: outcomes)
470
+ Tick.new(locked: false, outcomes: dry_run ? outcomes : mark_disabled(outcomes, started, links: links))
469
471
  end
470
472
 
471
473
  # Fire one entry now, whatever its next_due says (`chi schedule run-now`).
@@ -505,7 +507,8 @@ module Samagotchi
505
507
  if verdict
506
508
  kind, reason = verdict
507
509
  status = kind == :skip ? "skipped" : "failed"
508
- updated = status == "skipped" ? skipped(current, reason) : failed(current, reason)
510
+ updated = status == "skipped" ? skipped(current, reason) : failed(current, reason) if current.enabled
511
+ updated ||= current.with(last_result: reason)
509
512
  file.entries[position] = updated
510
513
  outcome = Outcome.new(id: current.id, title: current.title, status: status, detail: reason, entry: updated)
511
514
  next
@@ -515,10 +518,10 @@ module Samagotchi
515
518
  file.entries[position] = reserved
516
519
  end
517
520
 
518
- return outcome if outcome
521
+ return mark_disabled([outcome], [entry], links: links).first if outcome
519
522
  return Outcome.new(id: entry.id, title: entry.title, status: "failed", detail: "no such schedule") unless reserved
520
523
 
521
- fire_and_record(reserved, links)
524
+ mark_disabled([fire_and_record(reserved, links)], [entry], links: links).first
522
525
  end
523
526
 
524
527
  # Minutes between the hub's ticks when schedule.auto_tick is on.
@@ -695,7 +698,9 @@ module Samagotchi
695
698
  file.entries[position] = nil
696
699
  file.entries.compact!
697
700
  else
698
- file.entries[position] = entry.with(enabled: enabled, last_result: enabled ? "enabled" : "disabled")
701
+ changed = file.entries[position].with(enabled: enabled, last_result: enabled ? "enabled" : "disabled")
702
+ # Enabled again with a fresh budget: its next skip must not end it at once.
703
+ file.entries[position] = enabled ? changed.with(skips: 0, failures: 0) : changed
699
704
  end
700
705
  end
701
706
  entry
@@ -792,17 +797,47 @@ module Samagotchi
792
797
  enabled: one_off ? false : entry.enabled)
793
798
  end
794
799
 
800
+ # The skips and failures that turned off a recurring entry that was on when
801
+ # the pass began (+before+), as the file has it now: one diff covers every
802
+ # path that records one. A `date` one-off is spent, not disabled; an entry
803
+ # off within budget is an owner's `chi schedule disable`.
804
+ def mark_disabled(outcomes, before, links: nil)
805
+ ended = outcomes.select { |outcome| %w[skipped failed].include?(outcome.status) }.map(&:id)
806
+ status_by_id = outcomes.select { |outcome| %w[skipped failed].include?(outcome.status) }
807
+ .to_h { |outcome| [outcome.id, outcome.status] }
808
+ on = before.select { |entry| entry.enabled && entry.recurrence[:kind] != "date" && ended.include?(entry.id) }.map(&:id)
809
+ return outcomes if on.empty?
810
+
811
+ off = read.entries.grep(Entry).select do |entry|
812
+ budget_reached = case status_by_id[entry.id]
813
+ when "skipped" then entry.skips >= entry.max_skips
814
+ when "failed" then entry.failures >= entry.max_failures
815
+ else false
816
+ end
817
+ on.include?(entry.id) && !entry.enabled && budget_reached
818
+ end
819
+ links ||= links_now unless off.empty?
820
+ off.each do |entry|
821
+ index = outcomes.rindex { |outcome| outcome.id == entry.id && %w[skipped failed].include?(outcome.status) }
822
+ session_id = target_of(entry, links).first || entry.head
823
+ outcomes[index] = outcomes[index].with(disabled: true, entry: entry, session_id: session_id)
824
+ end
825
+ outcomes
826
+ end
827
+
795
828
  def skipped(entry, reason)
796
829
  skips = entry.skips + 1
797
- disabled = skips >= entry.max_skips
830
+ within_budget = skips < entry.max_skips
798
831
  entry.with(skips: skips, firing_since: nil, firing_token: nil, pending_session_id: nil, pending_turn_id: nil,
799
- last_result: disabled ? "disabled: #{reason}" : "skipped", enabled: !disabled)
832
+ last_result: within_budget ? "skipped" : "disabled: #{reason}",
833
+ enabled: within_budget && (entry.enabled || entry.recurrence[:kind] == "date"))
800
834
  end
801
835
 
802
836
  def failed(entry, reason)
803
837
  failures = entry.failures + 1
838
+ within_budget = failures < entry.max_failures
804
839
  entry.with(failures: failures, firing_since: nil, firing_token: nil, pending_session_id: nil, pending_turn_id: nil,
805
- last_result: reason, enabled: failures < entry.max_failures)
840
+ last_result: reason, enabled: within_budget && (entry.enabled || entry.recurrence[:kind] == "date"))
806
841
  end
807
842
 
808
843
  def pending_detail(entry)
@@ -1160,8 +1195,8 @@ module Samagotchi
1160
1195
  Outcome.new(id: entry.id, title: entry.title, status: status, detail: message, entry: entry)
1161
1196
  end
1162
1197
 
1163
- # A run-now refused before anything was tried: the same counters a tick
1164
- # moves for a skip or a failure. `due_was` is untouched — run-now is not a
1198
+ # A run-now refused before anything was tried: an enabled schedule moves
1199
+ # the same counters a tick does. `due_was` is untouched — run-now is not a
1165
1200
  # scheduled occurrence, so there is no occurrence to put the clock back to.
1166
1201
  # The result goes back under the lock before any pruning, so a prune that
1167
1202
  # raises midway cannot lose the new head.
@@ -34,7 +34,9 @@ module Samagotchi
34
34
  end
35
35
 
36
36
  # A /continue yes (or bare /continue) from a parent agent's process.
37
- def self.parent_continue?(prompt) = TurnFlow.continue_yes?(prompt) && Guardrails::ParentApprovals.parent_process?
37
+ def self.parent_continue?(prompt, env: ENV)
38
+ TurnFlow.continue_yes?(prompt) && Guardrails::ParentApprovals.parent_process?(env: env)
39
+ end
38
40
 
39
41
  # The first refusal of a parent's /continue yes among targets whose
40
42
  # own parent_answers are +values+, held to this process's config.yml
@@ -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 "delivery"
5
6
  require_relative "terminal_ui/formatting"
@@ -42,7 +43,6 @@ module Samagotchi
42
43
  include CLI::Command
43
44
  include CLI::ParentWait
44
45
 
45
- CLIENT_ID = ClientId::CLI_SEND
46
46
  # The cap on one turn's images the Bridge checks.
47
47
  MAX_IMAGES = ImageStore::MAX_TURN_REFS
48
48
  # A cut's outcomes in the Bridge's ack (SteerCut#cut_for_steer).
@@ -57,8 +57,8 @@ module Samagotchi
57
57
  def self.pause(seconds) = sleep(seconds)
58
58
 
59
59
  USAGE = <<~TEXT
60
- Usage: chi send [-m TEXT] [--image PATH]... [--cut | --queue] (ID|PREFIX)...
61
- chi send --new [--dir DIR] [--model M] [--llm-context LAYERS] [--thinking LEVEL] [--toolkit NAME] [--set KEY=VALUE]... [--parent-answers LEVEL] [-m TEXT] [--image PATH]...
60
+ Usage: chi send [-m TEXT] [--image PATH]... [--cut | --queue] [--as NAME] (ID|PREFIX)...
61
+ chi send --new [--dir DIR] [--model M] [--llm-context LAYERS] [--thinking LEVEL] [--toolkit NAME] [--set KEY=VALUE]... [--parent-answers LEVEL] [--driver NAME] [-m TEXT] [--image PATH]...
62
62
  chi send --new --continues (ID|PREFIX|last:ID) [--model M] [-m TEXT] [--image PATH]...
63
63
  chi send --wait [--timeout S] [--format json] [-m TEXT] [--image PATH]... (--new | ID)
64
64
  chi send --queue --wait [--timeout S] [--format json] [-m TEXT] ID
@@ -123,6 +123,17 @@ module Samagotchi
123
123
  questions: hard, standard or soft, only stricter than
124
124
  config.yml's guardrails.parent_answers (a looser one
125
125
  warns; config.yml's applies)
126
+ --driver NAME
127
+ (--new) name the agent NAME its driver (its messages go
128
+ in uncounted, with no header); an agent that creates
129
+ one drives it
130
+ --as NAME send as the agent NAME (agent:NAME; lowercase letters,
131
+ digits, - and _, up to 32), not as you. Without it, an
132
+ agent's marker names the sender (CLAUDECODE: claude,
133
+ CODEX_THREAD_ID: codex, AI_AGENT: its value; inside a
134
+ chi session its own, chi-ID8, and --as is ignored).
135
+ An agent's message restarts no stopped session, brings
136
+ back no archived one and runs no ! line
126
137
  --wait wait for the answer and print it (one session); the
127
138
  other lines go to stderr. Exit 3: it waits for an
128
139
  answer from you: the question, its options and the
@@ -191,6 +202,8 @@ module Samagotchi
191
202
  f.value "--timeout"
192
203
  f.value "--format"
193
204
  f.value "--turn"
205
+ f.value "--as", key: :as
206
+ f.value "--driver", key: :driver
194
207
  # Starting a turn in every live session at once is too easy to do
195
208
  # by accident.
196
209
  f.refuse "--all", "there is no --all: name the sessions"
@@ -258,8 +271,10 @@ module Samagotchi
258
271
  # @param argv [Array<String>] the arguments after "send"
259
272
  # @param access [SessionAccess::Local, nil] where the sessions are;
260
273
  # default this machine's, in +state_dir+
261
- def initialize(argv, stdin: $stdin, stdout: $stdout, stderr: $stderr, state_dir: nil, access: nil)
274
+ # @param env [Hash] where the agent markers are read (ENV; specs pass their own)
275
+ def initialize(argv, stdin: $stdin, stdout: $stdout, stderr: $stderr, state_dir: nil, access: nil, env: ENV)
262
276
  @argv = argv.dup
277
+ @env = env
263
278
  @stdin = stdin
264
279
  @stdout = stdout
265
280
  @stderr = stderr
@@ -279,6 +294,9 @@ module Samagotchi
279
294
  @waiting = options[:wait] == true
280
295
  @cut = options[:cut] == true
281
296
  @queue = options[:queue] == true
297
+ return CLI::Exit::USAGE unless (@agent = agent_name(options))
298
+
299
+ @agent = nil if @agent == :owner
282
300
  prompt = compose(utf8(read_stdin), utf8(options[:message]))
283
301
  # Before the wait-only case, which would drop the images.
284
302
  return usage_error("--image needs a message: pass -m TEXT or pipe it in") if prompt.nil? && !options[:images].empty?
@@ -377,7 +395,7 @@ module Samagotchi
377
395
  return usage_error("at most #{MAX_IMAGES} images") if options[:images].size > MAX_IMAGES
378
396
  return new_options(options) if options[:new]
379
397
 
380
- %i[dir model continues thinking toolkit].each { |key| return usage_error("--#{key} needs --new") if options[key] }
398
+ %i[dir model continues thinking toolkit driver].each { |key| return usage_error("--#{key} needs --new") if options[key] }
381
399
  TOOLKIT_FLAGS.each { |key, flag| return usage_error("#{flag} needs --new") unless Array(options[key]).empty? }
382
400
  LLM_CONTEXT_FLAGS.each { |key, flag| return usage_error("#{flag} needs --new") if options[key] }
383
401
  return usage_error("--set needs --new") unless Array(options[:sets]).empty?
@@ -396,6 +414,8 @@ module Samagotchi
396
414
 
397
415
  def new_options(options)
398
416
  return usage_error("--new takes no session ids: it starts one session") unless options[:ids].empty?
417
+ return usage_error("--driver takes an agent's name: lowercase letters, digits, - and _") if options[:driver] && !AgentCaller.clean(options[:driver])
418
+ return usage_error("--continues keeps the previous session's driver; leave out --driver") if options[:driver] && options[:continues]
399
419
 
400
420
  if options[:continues]
401
421
  taken = [("--dir" if options[:dir])] +
@@ -564,6 +584,8 @@ module Samagotchi
564
584
  setup = options[:setup_words] || SessionSetup.from_request(llm_context: options[:llm_context], thinking: options[:thinking],
565
585
  toolkit: options[:toolkit_value], settings: options[:settings],
566
586
  parent_answers: options[:parent_answers])
587
+ # --driver: the agent the owner names as its driver (Session#driver).
588
+ start[:driver] = ClientId.agent(AgentCaller.clean(options[:driver])) if options[:driver]
567
589
  SessionAccess::NewSession.new(**start, working_directory: options[:dir], model_name: options[:model], setup: setup)
568
590
  end
569
591
 
@@ -727,9 +749,24 @@ module Samagotchi
727
749
 
728
750
  SENT_COMMAND = "sent as a session command"
729
751
 
730
- # chi send's client id, or chi answer's for a parent agent's /continue
731
- # yes (the worker holds that to its guardrails.parent_answers).
732
- def client_id_for(prompt) = ParentGate.parent_continue?(prompt) ? ClientId::CLI_ANSWER : CLIENT_ID
752
+ # chi send's client id (an agent's, agent:<name>, when one sends:
753
+ # #agent_name), or chi answer's for a parent agent's /continue yes (the
754
+ # worker holds that to its guardrails.parent_answers): an agent's
755
+ # always is one, a marker-less process's when ParentGate says so.
756
+ def client_id_for(prompt)
757
+ continue = @agent ? TurnFlow.continue_yes?(prompt) : ParentGate.parent_continue?(prompt, env: @env)
758
+ continue ? ClientId::CLI_ANSWER : AgentCaller.send_id(name: @agent)
759
+ end
760
+
761
+ # Who sends (AgentCaller.send_name): the agent's name, :owner for none,
762
+ # or nil after a usage error (an --as that is not a name).
763
+ def agent_name(options)
764
+ name, error, note = AgentCaller.send_name(as: options[:as], env: @env)
765
+ return usage_error(error) && nil if error
766
+
767
+ @stderr.puts("chi send: #{note}") if note
768
+ name || :owner
769
+ end
733
770
 
734
771
  # Whether +text+ may be a session command, which only its worker knows
735
772
  # (a bundle's too).
@@ -290,6 +290,14 @@ module Samagotchi
290
290
  # continue) and an idle session. Set once, by spawn_session; a
291
291
  # continue and a fork don't carry it.
292
292
  SessionField.plain("first_turn_client_id", nil, optional: true),
293
+ # The agent that drives this session (agent:<name>, a ClientId): the
294
+ # one that created it (spawn_session, a prompt or none), or the one
295
+ # the owner named (chi send --new --driver, /driver). Its messages are
296
+ # as chi send's were (no header, never counted: Visitor); any other
297
+ # agent's are a visitor's. A continue keeps it
298
+ # (SessionContinue.spawn_continuation); a fork and a delegate child
299
+ # have none. nil: no agent drives it.
300
+ SessionField.plain("driver", nil, optional: true),
293
301
  # A Verify fresh child's requester, rules and claim (VerifyFreshOrigin),
294
302
  # nil for any other session. Set once, at spawn (VerifyFresh.start).
295
303
  # Autoloaded on the first one (the bundle test kit's load budget).
@@ -309,7 +317,7 @@ module Samagotchi
309
317
  attr_accessor :id, :metadata_version, :mode, :model_name, :model_typed, :working_directory, :messages,
310
318
  :created_at, :updated_at, :status, :last_prompt, :first_preview, :title, :test_run,
311
319
  :used_memory_names, :preloaded_memory_names, :muted_memory_names, :parent_id, :scratch,
312
- :continues, :first_turn_id, :first_turn_client_id, :project_id
320
+ :continues, :first_turn_id, :first_turn_client_id, :driver, :project_id
313
321
  attr_writer :project_root, :delegate
314
322
  attr_reader :appended_prompt_files, :written_by
315
323