samagotchi 0.195.0 → 0.196.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 (97) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +41 -1
  3. data/docs/architecture.md +2 -1
  4. data/docs/bundle-authoring.md +23 -23
  5. data/docs/bundles.md +11 -3
  6. data/docs/cli.md +4 -0
  7. data/docs/context.md +13 -3
  8. data/docs/guardrails.md +6 -4
  9. data/docs/hooks.md +3 -1
  10. data/docs/internals/block-renderers.md +4 -1
  11. data/docs/internals/engine.md +2 -1
  12. data/docs/internals/knowledge.md +15 -5
  13. data/docs/internals/participants.md +15 -3
  14. data/docs/internals/peers.md +12 -8
  15. data/docs/internals/session-lifecycle.md +26 -12
  16. data/docs/internals/web-frontend.md +64 -27
  17. data/docs/pages.md +1 -1
  18. data/docs/peers.md +1 -1
  19. data/docs/plugins.md +73 -3
  20. data/docs/sessions.md +1 -1
  21. data/docs/system-one.md +3 -1
  22. data/lib/samagotchi/bundle_manifest.rb +30 -5
  23. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  24. data/lib/samagotchi/bundles/cost-cap/manifest.yml +4 -4
  25. data/lib/samagotchi/bundles/cost-cap/plugin.rb +54 -3
  26. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  27. data/lib/samagotchi/bundles/github-pr/manifest.yml +4 -2
  28. data/lib/samagotchi/bundles/knowledge/chi_adapters.rb +43 -25
  29. data/lib/samagotchi/bundles/knowledge/manifest.yml +6 -4
  30. data/lib/samagotchi/bundles/knowledge/plugin.rb +37 -18
  31. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  32. data/lib/samagotchi/context_change.rb +44 -0
  33. data/lib/samagotchi/context_note.rb +1 -1
  34. data/lib/samagotchi/context_providers.rb +14 -0
  35. data/lib/samagotchi/context_sources.rb +3 -25
  36. data/lib/samagotchi/engine/plugins.rb +21 -0
  37. data/lib/samagotchi/events.rb +1 -0
  38. data/lib/samagotchi/guardrails/pair_boundary.rb +12 -4
  39. data/lib/samagotchi/guardrails/targets.rb +24 -2
  40. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  41. data/lib/samagotchi/memory_bundle/builder.rb +2 -1
  42. data/lib/samagotchi/memory_bundle/installed_copy.rb +2 -1
  43. data/lib/samagotchi/participants.rb +17 -6
  44. data/lib/samagotchi/peer_exchanges.rb +1 -2
  45. data/lib/samagotchi/peer_note.rb +38 -5
  46. data/lib/samagotchi/peer_presence.rb +20 -7
  47. data/lib/samagotchi/plugin/api.rb +5 -1
  48. data/lib/samagotchi/plugin/chips.rb +125 -0
  49. data/lib/samagotchi/plugin/context.rb +19 -1
  50. data/lib/samagotchi/plugin/peer_pairing.rb +2 -2
  51. data/lib/samagotchi/plugin/peer_start.rb +1 -1
  52. data/lib/samagotchi/plugin/peers.rb +5 -2
  53. data/lib/samagotchi/plugin/tool_spec.rb +19 -9
  54. data/lib/samagotchi/schedules.rb +8 -2
  55. data/lib/samagotchi/session_access/local.rb +34 -33
  56. data/lib/samagotchi/session_chain/sharing.rb +79 -0
  57. data/lib/samagotchi/session_chain/successor.rb +4 -2
  58. data/lib/samagotchi/session_chips.rb +133 -0
  59. data/lib/samagotchi/session_inbox_delivery.rb +11 -11
  60. data/lib/samagotchi/session_manager/emptiness.rb +4 -1
  61. data/lib/samagotchi/session_observer.rb +1 -1
  62. data/lib/samagotchi/session_stats.rb +5 -4
  63. data/lib/samagotchi/session_stores.rb +3 -0
  64. data/lib/samagotchi/speaker.rb +228 -0
  65. data/lib/samagotchi/steer.rb +36 -132
  66. data/lib/samagotchi/testing/bundle.rb +5 -0
  67. data/lib/samagotchi/testing/host.rb +1 -0
  68. data/lib/samagotchi/testing/recorder.rb +10 -0
  69. data/lib/samagotchi/tools/registry.rb +8 -3
  70. data/lib/samagotchi/turn_excerpts.rb +8 -4
  71. data/lib/samagotchi/version.rb +1 -1
  72. data/lib/samagotchi/web/app.rb +21 -10
  73. data/lib/samagotchi/web/participant_view.rb +1 -1
  74. data/lib/samagotchi/web/peer_routes.rb +5 -2
  75. data/lib/samagotchi/web/plugin_chip_rows.rb +39 -0
  76. data/lib/samagotchi/web/public/agent_rows.js +1 -0
  77. data/lib/samagotchi/web/public/app.js +17 -25
  78. data/lib/samagotchi/web/public/chains.js +0 -26
  79. data/lib/samagotchi/web/public/command_list.js +2 -3
  80. data/lib/samagotchi/web/public/composer.js +2 -3
  81. data/lib/samagotchi/web/public/composer_mount.js +3 -6
  82. data/lib/samagotchi/web/public/context_chips.js +240 -93
  83. data/lib/samagotchi/web/public/context_groups.js +84 -0
  84. data/lib/samagotchi/web/public/draft_follow.js +33 -0
  85. data/lib/samagotchi/web/public/drafts.js +26 -22
  86. data/lib/samagotchi/web/public/index.html +32 -0
  87. data/lib/samagotchi/web/public/peer_chip_kind.js +49 -0
  88. data/lib/samagotchi/web/public/peer_note.js +2 -2
  89. data/lib/samagotchi/web/public/peer_row.js +10 -5
  90. data/lib/samagotchi/web/public/peer_wait.js +4 -2
  91. data/lib/samagotchi/web/public/plugin_chip.js +55 -0
  92. data/lib/samagotchi/web/public/plugin_chip_kind.js +48 -0
  93. data/lib/samagotchi/web/public/send_turn.js +8 -21
  94. data/lib/samagotchi/web/public/session_actions.js +10 -23
  95. data/lib/samagotchi/web/public/session_view.js +7 -3
  96. data/lib/samagotchi/web/public/stream_handlers.js +2 -0
  97. metadata +12 -1
@@ -84,6 +84,13 @@ module Samagotchi
84
84
  # call's name.
85
85
  attr_reader :acts_as
86
86
 
87
+ # @return [Symbol, nil] a plugin tool's chi.tool(participant:) (its
88
+ # registered entry's: :deny, :allow; :deny too when the tool its
89
+ # call acts as is: .participant_of); nil for chi's own tools and
90
+ # for a call no entry answers. Guardrails::PairBoundary refuses a
91
+ # :deny one on a participant's turn.
92
+ attr_reader :participant
93
+
87
94
  # @return [String, nil] what a plugin tool's targets: says to name the
88
95
  # call by in the approval question (label:, "github: x"), in place of
89
96
  # the tool's registered label; display only (no rule or approval key
@@ -134,6 +141,7 @@ module Samagotchi
134
141
  cwd = base
135
142
  args = nil
136
143
  acts_as = nil
144
+ participant = nil
137
145
  label = nil
138
146
  writes = false
139
147
  env = {}
@@ -161,13 +169,14 @@ module Samagotchi
161
169
  entry = entry_of(tool, registry, surface)
162
170
  args = given[:args] || call[:args] if entry && !entry.core? && call[:args].is_a?(Hash)
163
171
  acts_as = given[:acts_as]
172
+ participant = participant_of(entry, acts_as, registry, surface)
164
173
  label = given[:label]
165
174
  end
166
175
  memory_remove = tool == "memory_write" && call[:remove].to_s.strip.downcase == "true"
167
176
  memory_overlay = tool == "memory_write" && !memory_remove && call[:current_model_only].to_s.strip.downcase == "true"
168
177
  memory = tool == "memory_write" ? memory_facts(call) : nil
169
178
  new(tool: tool, command: command, paths: paths.compact, cwd: cwd, env: env, repo_root: context.repo_root(cwd),
170
- repo: context.repo(cwd), args: args, acts_as: acts_as, label: label, writes: writes,
179
+ repo: context.repo(cwd), args: args, acts_as: acts_as, label: label, writes: writes, participant: participant,
171
180
  memory_remove: memory_remove,
172
181
  memory_overlay: memory_overlay, memory: memory,
173
182
  model_name: model_name, model_key: model_key, session_root: context.repo_root(base) || base,
@@ -243,6 +252,18 @@ module Samagotchi
243
252
  surface ? surface.registered[name] : registry&.[](name)
244
253
  end
245
254
 
255
+ # A plugin tool's call's participant: (Registry::Entry#participant):
256
+ # :deny when its entry or the tool its call acts as (call_tool's
257
+ # acts_as: a call whose inner args didn't unwrap) is declared so; else
258
+ # its entry's; nil for chi's own tools and a call with no entry.
259
+ def self.participant_of(entry, acts_as, registry, surface)
260
+ return nil unless entry && !entry.core?
261
+ return :deny if acts_as && entry_of(acts_as, registry, surface)&.participant == :deny
262
+
263
+ entry.participant
264
+ end
265
+ private_class_method :participant_of
266
+
246
267
  # The drops logged, per registry (a session's): each tool's acts_as
247
268
  # once, not at every call (targets run several times a call).
248
269
  DROPS_LOGGED = ObjectSpace::WeakKeyMap.new
@@ -336,8 +357,9 @@ module Samagotchi
336
357
  # @param env [Hash{String=>String}] the call's env: (.env_of)
337
358
  def initialize(tool:, command:, paths:, cwd:, repo_root:, env: {}, repo: nil, args: nil, acts_as: nil,
338
359
  label: nil, model_name: nil, model_key: nil, session_root: nil, chi_dirs: nil,
339
- memory_remove: false, memory_overlay: false, memory: nil, writes: false)
360
+ memory_remove: false, memory_overlay: false, memory: nil, writes: false, participant: nil)
340
361
  @env = env
362
+ @participant = participant
341
363
  @acts_as = acts_as
342
364
  @label = label
343
365
  @writes = writes
@@ -42,6 +42,10 @@ module Samagotchi
42
42
  # needs BundleManifest.parse_needs'
43
43
  # script_names the scripts/ files it lists
44
44
  # context_providers Array<ContextProviders::Provider>
45
+ # context_group the label the web's chips fold the bundle's
46
+ # sources under (context_group:): the kept
47
+ # manifest's only, nil from the record (so a
48
+ # missing, stale or edited kept file has none)
45
49
  # block_renderers Array<BlockRenderers::Renderer>
46
50
  # pages the page scripts (pages:, Pages::Bundled): the
47
51
  # kept manifest's only, [] from the record (a
@@ -65,7 +69,7 @@ module Samagotchi
65
69
  # the first chi that read it), {} from the record
66
70
  # origin :kept or :record
67
71
  class Manifest < Data.define(:name, :version, :requires_chi, :trust_level, :description, :needs,
68
- :script_names, :context_providers, :block_renderers, :pages, :session_settings,
72
+ :script_names, :context_providers, :context_group, :block_renderers, :pages, :session_settings,
69
73
  :session_setting_types, :settings, :setting_types, :file_descriptions,
70
74
  :plugin_required, :plugin_parts, :includes, :unknown_keys, :floor_keys, :problems,
71
75
  :origin)
@@ -137,6 +141,7 @@ module Samagotchi
137
141
  needs: pick.call("needs", kept.needs, mirrored.needs),
138
142
  script_names: pick.call("scripts", kept.scripts.keys, mirrored.script_names),
139
143
  context_providers: pick.call("context_providers", kept.context_providers, mirrored.context_providers),
144
+ context_group: pick.call("context_group", kept.context_group, mirrored.context_group),
140
145
  block_renderers: pick.call("block_renderers", kept.block_renderers, mirrored.block_renderers),
141
146
  pages: pick.call("pages", kept.pages, mirrored.pages),
142
147
  session_settings: session.session_settings, session_setting_types: session.session_setting_types,
@@ -163,6 +168,7 @@ module Samagotchi
163
168
  needs: parsed(problems, "needs", [], BundleManifest::ValidationError) { BundleManifest.parse_needs(raw["needs"]) },
164
169
  script_names: bundle.scripts.keys,
165
170
  context_providers: parsed(problems, "context_providers", []) { ContextProviders.parse_list(raw["context_providers"]) },
171
+ context_group: nil,
166
172
  block_renderers: parsed(problems, "block_renderers", []) { BlockRenderers.parse_list(raw["block_renderers"]) },
167
173
  pages: [],
168
174
  session_settings: list(raw["session_settings"]) || [],
@@ -203,7 +203,7 @@ module Samagotchi
203
203
  parts.scripts.each_value { |src| FileUtils.cp(src, File.join(staging, "scripts", File.basename(src))) }
204
204
  end
205
205
 
206
- # manifest.yml for the staged bundle: requires_chi, needs, session_settings and settings (typed) and the
206
+ # manifest.yml for the staged bundle: requires_chi, needs, context_group, session_settings and settings (typed) and the
207
207
  # file descriptions come from the installed bundle's manifest (InstalledBundles::Manifest), the
208
208
  # trust_level and description from the CLI else that manifest. A key of its kept manifest.yml
209
209
  # this chi doesn't know is carried as installed (the build is the bundle again), with a warning.
@@ -227,6 +227,7 @@ module Samagotchi
227
227
  needs: manifest&.needs,
228
228
  scripts: parts.scripts.transform_values { |src| InstalledBundles::FileDigest.sha256(src) },
229
229
  context_providers: parts.context_providers,
230
+ context_group: manifest&.context_group,
230
231
  block_renderers: parts.block_renderers,
231
232
  pages: manifest&.pages || [],
232
233
  file_descriptions: manifest ? manifest.file_descriptions.slice(*files_map.keys) : {},
@@ -49,7 +49,8 @@ module Samagotchi
49
49
  plugin: plugin(bundle, provenance, dir),
50
50
  scripts: copies(bundle.scripts, provenance.scripts_dir, File.join(dir, "scripts")),
51
51
  requires_chi: manifest.requires_chi, needs: manifest.needs,
52
- context_providers: manifest.context_providers, block_renderers: manifest.block_renderers, pages: manifest.pages,
52
+ context_providers: manifest.context_providers, context_group: manifest.context_group, block_renderers: manifest.block_renderers,
53
+ pages: manifest.pages,
53
54
  session_settings: manifest.session_settings, session_setting_types: manifest.session_setting_types,
54
55
  settings: manifest.settings, setting_types: manifest.setting_types
55
56
  )
@@ -7,7 +7,7 @@ require_relative "atomic_file"
7
7
  require_relative "participant_messages"
8
8
  require_relative "archive_store"
9
9
  require_relative "session"
10
- require_relative "session_transition"
10
+ require_relative "session_chain/sharing"
11
11
  require_relative "grants"
12
12
  require_relative "participant_turn_mode"
13
13
 
@@ -124,11 +124,13 @@ module Samagotchi
124
124
  identity = Grants.clean_identity(identity) unless identity.nil?
125
125
  raise Grants::Unbindable if !identity.nil? && public_url&.identity_header.nil?
126
126
 
127
- # Checked and issued under the session's transition lock shared: a
128
- # continue archives the link and ends its grants (end_sessions), so
129
- # one issued between the two would outlive the archive.
130
- issued = SessionTransition.shared(session_id, state_dir: state_dir) do |free|
131
- raise Grants::Invalid, SessionTransition::Busy.held(session_id, state_dir: state_dir).message unless free
127
+ # Checked and issued under the session's transition lock shared
128
+ # (SessionChain::Sharing): a continue archives the link and ends its
129
+ # grants (end_sessions), so one issued between the two would outlive
130
+ # the archive. Refused while a transition holds it: naming who
131
+ # continues the session (#held_refusal), else the holder's Busy words.
132
+ issued = SessionChain::Sharing.under(session_id, state_dir: state_dir) do |sharing|
133
+ raise Grants::Invalid, held_refusal(sharing) if sharing
132
134
  if ArchiveStore.archived?(Session.session_dir(session_id, state_dir: state_dir))
133
135
  raise Grants::Invalid, "session #{session_id[0, 8]} is archived: unarchive it to invite anyone"
134
136
  end
@@ -143,6 +145,15 @@ module Samagotchi
143
145
  issued
144
146
  end
145
147
 
148
+ # An invite's words for a held lock (SessionChain::Sharing's value):
149
+ # the session that continues it, under any holder (a continue's new
150
+ # link in flight: "in a moment", it may not be saved yet), else Busy's.
151
+ def held_refusal(sharing)
152
+ return sharing.busy.message if sharing.is_a?(SessionChain::Sharing::Held)
153
+
154
+ "#{sharing.refusal.message}: invite there#{" in a moment" if sharing.in_flight?}"
155
+ end
156
+
146
157
  # Sets participant +id+'s cap on +session_id+ (chi share cap): the
147
158
  # grant, the sidecar (the worker's check) and the audit line.
148
159
  # @return [Grants::Grant, nil] nil when +id+ isn't an active grant there
@@ -75,9 +75,8 @@ module Samagotchi
75
75
  end
76
76
 
77
77
  def answer_row(entry)
78
- verdict = entry["summary"].to_s.scan(PeerNote::VERDICT).last&.first
79
78
  { summary: entry["summary"], at: entry["at"], serial: entry["serial"],
80
- verdict: (verdict if PeerNote::VERDICTS.include?(verdict)) }.compact
79
+ verdict: PeerNote.verdict_of(entry["summary"]) }.compact
81
80
  end
82
81
  end
83
82
  end
@@ -91,6 +91,9 @@ module Samagotchi
91
91
  VERDICT = /\bVERDICT:?\s*([A-Z]+)(?![A-Za-z|])/
92
92
  # The verdicts a note's peer hash names (.payload); another word is none.
93
93
  VERDICTS = %w[OK CHANGES UNSURE].freeze
94
+ # JavaScript's \s (.said: peer_row.js summaryWithoutVerdict's own white
95
+ # space, so the two agree on any summary).
96
+ JS_SPACE = "\t\n\v\f\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
94
97
 
95
98
  # The mailbox's note (a peer's message, PeerMailbox): its opening line,
96
99
  # approved by the owner; its source; how its lines point at a message
@@ -180,7 +183,35 @@ module Samagotchi
180
183
 
181
184
  # Whether a peer's answer agrees: the last verdict in its summary is
182
185
  # OK. Its wake (when it asked) closes the round (AGREED_LINE).
183
- def agrees?(summary) = summary.to_s.scan(VERDICT).last&.first == "OK"
186
+ def agrees?(summary) = verdict_of(summary) == "OK"
187
+
188
+ # A peer's verdict: the last VERDICT mark in its +summary+, nil unless
189
+ # it is one of VERDICTS. The one parser of .payload, .agrees? and
190
+ # PeerExchanges' answer rows.
191
+ def verdict_of(summary)
192
+ verdict = summary.to_s.scan(VERDICT).last&.first
193
+ verdict if VERDICTS.include?(verdict)
194
+ end
195
+
196
+ # The +summary+ the peer row shows: without its last VERDICT mark when
197
+ # that mark is +verdict+ (.verdict_of's), the punctuation it leaves
198
+ # tidied, white space squashed. The port of peer_row.js
199
+ # summaryWithoutVerdict (kept for notes saved before .payload's "said");
200
+ # spec/fixtures/peer_said_cases.json holds the cases both run.
201
+ def said(summary, verdict)
202
+ text = summary.to_s
203
+ last = text.to_enum(:scan, VERDICT).map { ::Regexp.last_match }.last
204
+ return squash(text) unless last && verdict && last[1] == verdict
205
+
206
+ before = last.pre_match.sub(/[#{JS_SPACE}(\[]+\z/o, "")
207
+ after = last.post_match.sub(/\A[#{JS_SPACE})\]]*[,;.:—–-]?[#{JS_SPACE}]*/o, "")
208
+ joined = squash("#{before} #{after}").gsub(/\([#{JS_SPACE}]*\)|\[[#{JS_SPACE}]*\]/o, "")
209
+ squash(joined.sub(/[#{JS_SPACE},;:—–-]+\z/o, ""))
210
+ end
211
+
212
+ # +text+'s white space runs as one space, none at its ends (JavaScript's
213
+ # replace(/\s+/g, " ").trim()).
214
+ def squash(text) = text.gsub(/[#{JS_SPACE}]+/o, " ").gsub(/\A +| +\z/, "")
184
215
 
185
216
  # A peer's +text+ for its note: { text: } up to +cap+ (+held+: a note
186
217
  # that doesn't wake, up to HELD_CHARS when that is less), { long:
@@ -196,12 +227,14 @@ module Samagotchi
196
227
  # A peer's note's payload, whose answer it is (the UIs draw it; the
197
228
  # model's content doesn't carry it): the peer's +peer+ and +label+, +re+
198
229
  # (the send it names), +summary+, +serial+, +verdict+ (the summary's
199
- # last, one of VERDICTS), +agreed+ (.agrees?) and +inline+ (true: the
200
- # note holds the text, .body); string keys, nils dropped.
230
+ # last, one of VERDICTS: .verdict_of), +said+ (the summary without that
231
+ # verdict, .said: the web's peer row; only with a verdict), +agreed+
232
+ # (.agrees?) and +inline+ (true: the note holds the text, .body); string
233
+ # keys, nils dropped.
201
234
  def payload(peer:, label:, re:, summary:, serial:, inline: false)
202
- verdict = summary.to_s.scan(VERDICT).last&.first
235
+ verdict = verdict_of(summary)
203
236
  { "peer" => peer, "label" => label, "re" => re, "summary" => summary, "serial" => serial,
204
- "verdict" => (verdict if VERDICTS.include?(verdict)), "agreed" => agrees?(summary),
237
+ "verdict" => verdict, "said" => (said(summary, verdict) if verdict), "agreed" => verdict == "OK",
205
238
  "inline" => (true if inline) }.compact
206
239
  end
207
240
  end
@@ -29,6 +29,8 @@ module Samagotchi
29
29
  PAIRED = "paired"
30
30
  # How long a mark waits (owner decision 3: a constant).
31
31
  WAIT_SECONDS = 600
32
+ # The longest product name a wait mark keeps (PeerWaiting's +app+).
33
+ APP_CHARS = 60
32
34
  # A peer session's id as a file name: Claude Code's uuid, a Codex thread.
33
35
  PEER_SESSION_RE = /\A[A-Za-z0-9][A-Za-z0-9-]{0,63}\z/
34
36
  FILE_MAX_BYTES = 8192
@@ -55,17 +57,26 @@ module Samagotchi
55
57
  end
56
58
  end
57
59
 
58
- # A chi +session+ that waits for a peer of its +project+ since +at+.
59
- PeerWaiting = Data.define(:session, :project, :at) do
60
- def to_h = { "session" => session, "project" => project, "at" => at }
60
+ # A chi +session+ that waits for a peer of its +project+ since +at+;
61
+ # +app+: the peer's product name as its bundle words it ("Claude Code":
62
+ # chi web's waiting chip, which loads no plugins), nil from an older
63
+ # worker's mark.
64
+ PeerWaiting = Data.define(:session, :project, :at, :app) do
65
+ def initialize(session:, project:, at:, app: nil) = super
66
+
67
+ def to_h = { "session" => session, "project" => project, "at" => at, "app" => app }.compact
61
68
 
62
69
  def self.from_h(data)
63
70
  return nil unless data.is_a?(Hash) && SessionPaths.valid_id?(data["session"].to_s)
64
71
  return nil unless [data["project"], data["at"]].all? { |value| value.nil? || value.is_a?(String) }
65
72
 
66
- new(session: data["session"], project: data["project"], at: data["at"])
73
+ new(session: data["session"], project: data["project"], at: data["at"], app: app_of(data["app"]))
67
74
  end
68
75
 
76
+ # +value+ as an +app+: a String of 1 to APP_CHARS characters, else
77
+ # none (any peer can write the folder).
78
+ def self.app_of(value) = (value if value.is_a?(String) && !value.empty? && value.length <= APP_CHARS)
79
+
69
80
  # When the wait ends; nil for an unparsable +at+.
70
81
  def until_at
71
82
  Time.iso8601(at.to_s) + WAIT_SECONDS
@@ -161,12 +172,14 @@ module Samagotchi
161
172
  false
162
173
  end
163
174
 
164
- # Session +session+ waits for +peer+ (written whole; again: a new wait).
175
+ # Session +session+ waits for +peer+ (written whole; again: a new wait),
176
+ # +app+ the peer's product name (PeerWaiting).
165
177
  # @return [PeerWaiting]
166
- def wait!(peer, session:, project:, state_dir: nil, now: Time.now)
178
+ def wait!(peer, session:, project:, app: nil, state_dir: nil, now: Time.now)
167
179
  SessionPaths.check_id!(session)
168
180
  dir = writable_dir(peer, WAITING, state_dir: state_dir)
169
- mark = PeerWaiting.new(session: session, project: project, at: now.utc.iso8601)
181
+ mark = PeerWaiting.new(session: session, project: project, at: now.utc.iso8601,
182
+ app: PeerWaiting.app_of(app))
170
183
  AtomicFile.write(File.join(dir, "#{session}.json"), "#{JSON.generate(mark.to_h)}\n")
171
184
  mark
172
185
  end
@@ -80,7 +80,11 @@ module Samagotchi
80
80
  "ctx.sessions.list" => "0.195.0",
81
81
  "ctx.sessions.present_ids" => "0.195.0",
82
82
  "ctx.context.snapshots" => "0.195.0",
83
- "ctx.panes.open(in:)" => "0.195.0"
83
+ "ctx.panes.open(in:)" => "0.195.0",
84
+ "ctx.peers.wait(app:)" => "0.196.0",
85
+ "ctx.speaker" => "0.196.0",
86
+ "chi.tool(participant:)" => "0.196.0",
87
+ "ctx.chips" => "0.196.0"
84
88
  }.freeze
85
89
 
86
90
  # chi.on's on_error: values. :log (the default) logs a raise and goes
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+ require_relative "card"
5
+
6
+ module Samagotchi
7
+ module Plugin
8
+ # ctx.chips (docs/plugins.md, Chips): a bundle's own chips in the web's
9
+ # session bar, after the peer chips and the sources. A chip is a label
10
+ # (with an age when it has a time), one of core's three looks, an
11
+ # optional dot, and a small card a tap opens: a markdown body and up to
12
+ # MAX_ACTIONS buttons, as a card's. Stored with the session
13
+ # (SessionChips), so chi web shows them with no worker running; a change
14
+ # announces :chips_updated and an open tab reads them again. The same
15
+ # chip again writes nothing. A bundle sees and changes only its own.
16
+ class Chips
17
+ # A source name's rules (ContextSources::NAME_RE): the strip's key is
18
+ # chip:<bundle>/<name>.
19
+ NAME = /\A[a-z0-9][a-z0-9-]{0,39}\z/
20
+ STATES = %i[ok warn error].freeze
21
+ MAX_LABEL = 40
22
+ MAX_TITLE = 200
23
+ MAX_BODY = 4_000
24
+ MAX_ACTIONS = 4
25
+ MAX_CHIPS = 3
26
+
27
+ # @param bundle [String]
28
+ # @param store [#call] → the session's store (SessionChips; the test
29
+ # kit's SessionChips::Memory), nil with no session yet
30
+ def initialize(bundle, store)
31
+ @bundle = bundle.to_s
32
+ @store = store
33
+ end
34
+
35
+ def inspect = "#<#{self.class.name} bundle=#{@bundle}>"
36
+
37
+ # Set chip +name+ (a new one, or a change to it).
38
+ # @param label [String] one line, at most MAX_LABEL characters (cut)
39
+ # @param state [Symbol] :ok, :warn or :error
40
+ # @param dot [Boolean] a dot on the chip
41
+ # @param title [String, nil] its tooltip
42
+ # @param at [Time, String, nil] a time the web shows as an age that
43
+ # ticks (" · 3m")
44
+ # @param body [String] the card's text, markdown as a card's
45
+ # @param actions [Array<Hash>] a card's actions (Card.build_action),
46
+ # at most MAX_ACTIONS
47
+ # @return [Boolean] whether it changed anything (false: the same chip
48
+ # again, or no session yet)
49
+ # @raise [ArgumentError] a bad name, label, state, time or action; more
50
+ # than MAX_ACTIONS actions; a chip past MAX_CHIPS for the bundle
51
+ def set(name, label:, state: :ok, dot: false, title: nil, at: nil, body: "", actions: [])
52
+ name = check_name(name)
53
+ chip = self.class.build(label: label, state: state, dot: dot, title: title, at: at, body: body, actions: actions)
54
+ store = @store.call or return false
55
+
56
+ store.update(@bundle) do |mine|
57
+ if !mine.key?(name) && mine.size >= MAX_CHIPS
58
+ raise ArgumentError, "a bundle has at most #{MAX_CHIPS} chips (#{@bundle}: #{mine.keys.join(", ")})"
59
+ end
60
+
61
+ mine.merge(name => chip)
62
+ end
63
+ end
64
+
65
+ # @return [Boolean] whether there was one
66
+ def remove(name)
67
+ name = check_name(name)
68
+ store = @store.call or return false
69
+
70
+ store.update(@bundle) { |mine| mine.except(name) }
71
+ end
72
+
73
+ # @return [Hash{String => Hash}] this bundle's chips now, by name
74
+ # (symbol keys: label, state, dot, title, at, body, actions, set_at)
75
+ def list
76
+ store = @store.call or return {}
77
+
78
+ (store.all[@bundle] || {}).transform_values { |chip| chip.transform_keys(&:to_sym) }
79
+ end
80
+
81
+ # A chip as stored (string keys, without its stamp).
82
+ # @raise [ArgumentError] as #set
83
+ def self.build(label:, state:, dot:, title:, at:, body:, actions:)
84
+ label = Card.one_line(label, MAX_LABEL)
85
+ raise ArgumentError, "a chip needs a label" if label.empty?
86
+
87
+ state = state.to_s.to_sym
88
+ raise ArgumentError, "a chip's state is one of #{STATES.join(", ")}" unless STATES.include?(state)
89
+ raise ArgumentError, "a chip's dot: is true or false" unless [true, false].include?(dot)
90
+
91
+ body = body.to_s
92
+ raise ArgumentError, "a chip's body is at most #{MAX_BODY} characters" if body.length > MAX_BODY
93
+
94
+ actions = Array(actions)
95
+ raise ArgumentError, "a chip has at most #{MAX_ACTIONS} actions" if actions.size > MAX_ACTIONS
96
+
97
+ title = title.nil? ? nil : Card.one_line(title, MAX_TITLE)
98
+ { "label" => label, "state" => state.to_s, "dot" => dot, "title" => title.to_s.empty? ? nil : title,
99
+ "at" => time(at), "body" => body,
100
+ "actions" => actions.map { |action| Card.build_action(action).transform_keys(&:to_s) } }
101
+ end
102
+
103
+ # @return [String, nil] +at+ as UTC ISO 8601
104
+ def self.time(at)
105
+ case at
106
+ when nil then nil
107
+ when Time then at.utc.iso8601
108
+ when String then Time.iso8601(at).utc.iso8601
109
+ else raise ArgumentError, "a chip's at: is a Time or an ISO 8601 string"
110
+ end
111
+ rescue ArgumentError
112
+ raise ArgumentError, "a chip's at: is a Time or an ISO 8601 string, not #{at.to_s[0, 40].inspect}"
113
+ end
114
+
115
+ private
116
+
117
+ def check_name(name)
118
+ name = name.to_s
119
+ raise ArgumentError, "a chip's name is lowercase letters, digits and -, at most 40: #{name[0, 40].inspect}" unless NAME.match?(name)
120
+
121
+ name
122
+ end
123
+ end
124
+ end
125
+ end
@@ -11,6 +11,7 @@ require_relative "../idle_client"
11
11
  require_relative "../tool_ids"
12
12
  require_relative "../cache_confirm"
13
13
  require_relative "../user_typed"
14
+ require_relative "../speaker"
14
15
  require_relative "service"
15
16
  require_relative "side_question"
16
17
 
@@ -40,6 +41,7 @@ module Samagotchi
40
41
  autoload :HttpCancelled, File.expand_path("http_errors", __dir__)
41
42
  autoload :Judgments, File.expand_path("judgments", __dir__)
42
43
  autoload :Secrets, File.expand_path("secrets", __dir__)
44
+ autoload :Chips, File.expand_path("chips", __dir__)
43
45
  autoload :SignIn, File.expand_path("sign_in", __dir__)
44
46
  # ctx.project's value: it reads the guardrails' denylist, which a
45
47
  # plugin that never asks (and the bundle test kit) doesn't load.
@@ -92,12 +94,15 @@ module Samagotchi
92
94
  # (Engine#start_sign_in; the test kit's opens no port).
93
95
  # +turn_interactive+ returns whether the running turn came from a screen
94
96
  # that can answer a question (ClientId.interactive?: a web tab, a TUI).
97
+ # +chips+ returns the session's chip store ctx.chips writes through
98
+ # (SessionChips, announcing :chips_updated; the test kit's in memory),
99
+ # nil with no session yet.
95
100
  Host = Struct.new(:session_id, :cwd, :messages, :messages_partial, :notify, :ask_user, :cancelled, :card,
96
101
  :ask_model, :model_name, :model_key, :state_dir, :scratch, :setup, :prompt_files,
97
102
  :steer, :stop_turn, :stop_generation, :frontend, :toolkit, :declared_tools, :use_toolkit, :load_tools,
98
103
  :cancel_controller, :cost, :usage, :turn_author, :cache_confirm, :model_names,
99
104
  :candidate_proposed, :judgments, :turn_running, :current_cancel, :secrets_store,
100
- :sign_in, :turn_interactive, keyword_init: true)
105
+ :sign_in, :turn_interactive, :chips, keyword_init: true)
101
106
 
102
107
  # ctx.ask_model failed: the model couldn't be reached, timed out, or
103
108
  # sent nothing usable. The message says why, for the user.
@@ -383,6 +388,12 @@ module Samagotchi
383
388
  Array(@host.messages.call).map { |message| message.dup.freeze }.freeze
384
389
  end
385
390
 
391
+ # Who wrote +message+ (an entry of #messages or ctx.sessions.read):
392
+ # :owner, :participant, :chi, :sender, :plugin, :model or :tool; nil
393
+ # for a non-Hash (Speaker.of). The message's keys stay chi's own.
394
+ # @return [Symbol, nil]
395
+ def speaker(message) = Speaker.of(message)
396
+
386
397
  # The newest answer's text as the user saw it (AnswerText.visible): the
387
398
  # newest bubble of #messages, its thoughts (a cut-off one too) and call
388
399
  # markup out. Mid-turn a worker's can be the running turn's interim text.
@@ -573,6 +584,13 @@ module Samagotchi
573
584
  @secrets ||= Secrets.new(@host.secrets_store.call(@bundle))
574
585
  end
575
586
 
587
+ # The bundle's own chips in the web's session bar (Chips,
588
+ # docs/plugins.md): set, remove, list.
589
+ # @return [Chips]
590
+ def chips
591
+ @chips ||= Chips.new(@bundle, -> { @host.chips&.call })
592
+ end
593
+
576
594
  # Send the session's owner to an address and get back the address the
577
595
  # browser was sent to (SignIn, docs/plugins.md, Sign-in): a card with
578
596
  # +button+, a loopback listener, /callback for a browser elsewhere.
@@ -55,7 +55,7 @@ module Samagotchi
55
55
  def pair_or_wait(ctx)
56
56
  peer = self.class
57
57
  unless announces?
58
- ctx.peers.wait(peer::PEER)
58
+ ctx.peers.wait(peer::PEER, app: peer::APP)
59
59
  return "waiting for a #{peer::APP} session (#{wait_minutes} min): say \"pair with chi\" in #{peer::NAME} " \
60
60
  "(#{peer::NAME} doesn't list itself here)"
61
61
  end
@@ -63,7 +63,7 @@ module Samagotchi
63
63
  here = ctx.peers.here(peer::PEER)
64
64
  return pair_with(ctx, here.first) if here.size == 1
65
65
 
66
- ctx.peers.wait(peer::PEER)
66
+ ctx.peers.wait(peer::PEER, app: peer::APP)
67
67
  return "waiting for a #{peer::APP} session: start one in this project (#{wait_minutes} min)" if here.empty?
68
68
 
69
69
  here_card(ctx, here)
@@ -122,7 +122,7 @@ module Samagotchi
122
122
  def open_started(ctx)
123
123
  peer = self.class
124
124
  open = ctx.peers.waiting(peer::PEER)
125
- written = ctx.peers.wait(peer::PEER) unless open && !open.stale?
125
+ written = ctx.peers.wait(peer::PEER, app: peer::APP) unless open && !open.stale?
126
126
  title = started_title(ctx)
127
127
  where, unknown = open_in(ctx)
128
128
  placed = nil
@@ -85,9 +85,12 @@ module Samagotchi
85
85
  PeerPresence.here(name.to_s, project: key, state_dir: state_dir)
86
86
  end
87
87
 
88
- # This session starts waiting for +name+ (10 minutes; again: anew).
88
+ # This session starts waiting for +name+ (10 minutes; again: anew);
89
+ # +app+: the peer's product name ("Claude Code"), chi web's waiting chip's.
89
90
  # @return [PeerPresence::PeerWaiting]
90
- def wait(name) = PeerPresence.wait!(name.to_s, session: session_id!, project: project, state_dir: state_dir)
91
+ def wait(name, app: nil)
92
+ PeerPresence.wait!(name.to_s, session: session_id!, project: project, app: app, state_dir: state_dir)
93
+ end
91
94
 
92
95
  # Ends this session's wait for +name+ when it is still +mark+ (the
93
96
  # one #wait returned: a start whose window didn't open), leaving any other
@@ -12,18 +12,23 @@ module Samagotchi
12
12
  # description:, parameters:}); the block, preview:, targets: and refs:
13
13
  # never do. +declare+ is which toolkits declare it (DECLARE: nil, as a
14
14
  # built-in is; :kit, only a kit that adds it; :always, every kit that
15
- # doesn't remove it: Toolkit::Resolved#declares?).
16
- class ToolSpec < Data.define(:name, :schema, :label, :preview, :targets, :refs, :block, :declare)
15
+ # doesn't remove it: Toolkit::Resolved#declares?). +participant+ is
16
+ # whether a participant's pair turn may call it (PARTICIPANT: :allow,
17
+ # the default; :deny, Guardrails::PairBoundary refuses it before any
18
+ # check or ask).
19
+ class ToolSpec < Data.define(:name, :schema, :label, :preview, :targets, :refs, :block, :declare, :participant)
17
20
  TOOL_NAME = /\A[a-z][a-z0-9_]{0,47}\z/
18
21
  PARAM_NAME = /\A[a-z_][a-z0-9_]*\z/i
19
22
  # chi.tool(declare:)'s values; nil (omitted) is a built-in's rule.
20
23
  DECLARE = %i[kit always].freeze
24
+ # chi.tool(participant:)'s values (default :allow).
25
+ PARTICIPANT = %i[allow deny].freeze
21
26
 
22
27
  # A checked tool declaration from #tool's arguments (Api#tool and
23
28
  # ToolSet#tool pass theirs on, so a new keyword is added here).
24
29
  # @return [ToolSpec]
25
30
  def self.build(name, description, params: {}, schema: nil, label: nil, preview: nil, targets: nil, refs: nil,
26
- declare: nil, &block)
31
+ declare: nil, participant: :allow, &block)
27
32
  raise ArgumentError, "tool #{name.inspect} needs a block" unless block
28
33
 
29
34
  name = name.to_s
@@ -34,19 +39,24 @@ module Samagotchi
34
39
  unless declare.nil? || DECLARE.include?(declare)
35
40
  raise ArgumentError, "tool #{name}: declare must be :kit or :always (got #{declare.inspect})"
36
41
  end
42
+ unless PARTICIPANT.include?(participant)
43
+ raise ArgumentError, "tool #{name}: participant must be :allow or :deny (got #{participant.inspect})"
44
+ end
37
45
 
38
46
  parameters = schema ? schema_parameters(name, schema) : params_schema(name, params)
39
47
  new(name: name, schema: { name: name, description: description.to_s, parameters: parameters },
40
- label: label&.to_s, preview: preview, targets: targets, refs: refs, block: block, declare: declare)
48
+ label: label&.to_s, preview: preview, targets: targets, refs: refs, block: block, declare: declare,
49
+ participant: participant)
41
50
  end
42
51
 
43
52
  # Make +bundle+'s tools in +registry+ the +specs+: its tools not in
44
53
  # them go; a new one, or one whose schema or label changed, is
45
54
  # registered (a changed one again, in its place: Tools::Registry
46
55
  # orders bundle tools by bundle and name); an unchanged one is kept
47
- # as it is, but for its block, preview:, targets: and refs:, swapped
48
- # in place (a changed declare: is a change: it moves the tool between
49
- # declared and not): none of them reaches the prompt, so not a change (that
56
+ # as it is, but for its block, preview:, targets:, refs: and
57
+ # participant:, swapped in place, so the next call reads them (a
58
+ # changed declare: is a change: it moves the tool between declared and
59
+ # not): none of them reaches the prompt, so not a change (that
50
60
  # would build the prompts again). A name
51
61
  # another source has is left out. Called on the turn thread
52
62
  # (Engine#apply_staged_tools!).
@@ -57,7 +67,7 @@ module Samagotchi
57
67
  registry.by_source(bundle).each do |entry|
58
68
  if (spec = wanted[entry.name]) && spec.schema == entry.schema && spec.label == entry.label &&
59
69
  spec.declare == entry.declare
60
- spec.entry_fields(context).slice(:handler, :preview, :targets, :refs).each { |key, value| entry[key] = value }
70
+ spec.entry_fields(context).slice(:handler, :preview, :targets, :refs, :participant).each { |key, value| entry[key] = value }
61
71
  next
62
72
  end
63
73
 
@@ -155,7 +165,7 @@ module Samagotchi
155
165
  preview = per_call(self.preview, parameters)
156
166
  targets = per_call(self.targets, parameters)
157
167
  {
158
- schema: schema, label: label, declare: declare,
168
+ schema: schema, label: label, declare: declare, participant: participant,
159
169
  handler: lambda { |call, _kctx|
160
170
  result = block.call(ToolSpec.args_of(call, parameters), context)
161
171
  ToolSpec.result_text(result)