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
@@ -25,6 +25,12 @@
25
25
  # cap:, else child: for a delegate, else default:.
26
26
  # The cap is resolved once per session id (ctx.delegate? parses the session
27
27
  # file) and kept until /cap or Continue writes a new one.
28
+ #
29
+ # The web's session bar shows a chip (ctx.chips; skipped on a chi without it):
30
+ # "cap · $4.10 of $5.00", warn at warn_at, error at the cap, its card's
31
+ # buttons raising the cap to twice it or turning it off. Set after each
32
+ # generation (ctx.cost counts it by then) and by /cap and Continue; the same
33
+ # label again writes nothing. None without a cap or a price.
28
34
  require "json"
29
35
 
30
36
  class Plugin
@@ -48,9 +54,13 @@ class Plugin
48
54
 
49
55
  def register(chi)
50
56
  chi.on(:before_generation) { |_event, ctx| check(ctx) }
51
- # Only the "can't be enforced" notice: a turn of one generation (or a
52
- # session's last) has no next before_generation to give it.
53
- chi.on(:after_generation) { |_event, ctx| check_known(ctx) }
57
+ # The "can't be enforced" notice (a turn of one generation, or a
58
+ # session's last, has no next before_generation to give it) and the
59
+ # chip: the spend now counts this generation.
60
+ chi.on(:after_generation) do |_event, ctx|
61
+ check_known(ctx)
62
+ show_chip(ctx)
63
+ end
54
64
  chi.command("/cap", "see or set this session's cost cap: /cap, /cap 5, /cap off", anytime: true) do |args, ctx|
55
65
  command(args, ctx)
56
66
  end
@@ -121,6 +131,45 @@ class Plugin
121
131
  ctx.notify("#{money(total)} of #{money(cap)} spent (#{(total / cap * 100).floor}%)", level: :warn)
122
132
  end
123
133
 
134
+ # The session bar's chip, from the cap now and the spend: removed with
135
+ # no cap or no price (as the cap isn't enforced then). Only informs: a
136
+ # failure is logged.
137
+ def show_chip(ctx)
138
+ return unless ctx.respond_to?(:chips)
139
+
140
+ resolved = resolve(ctx)
141
+ cap = resolved[:cap]
142
+ return ctx.chips.remove("cap") unless cap
143
+
144
+ cost = ctx.cost
145
+ return ctx.chips.remove("cap") unless cost.known?
146
+
147
+ total = cost.total
148
+ ctx.chips.set("cap", label: "cap · #{money(total)} of #{money(cap)}", state: chip_state(ctx, total, cap),
149
+ title: "cost-cap: #{(total / cap * 100).floor}% of this session's cap",
150
+ body: "This session has used **#{money(total)}** of its **#{money(cap)}** cap.\n\n" \
151
+ "At the cap the turn pauses and asks: continue for another " \
152
+ "#{round_money(resolved[:step] || cap)}, or stop.",
153
+ actions: [{ label: "Raise to #{round_money(cap * 2)}", command: "/cap #{amount_text(cap * 2)}",
154
+ primary: true },
155
+ { label: "Turn the cap off", command: "/cap off" }])
156
+ rescue StandardError => e
157
+ ctx.log.warn(:cap_chip_failed, error: "#{e.class}: #{e.message}")
158
+ end
159
+
160
+ def chip_state(ctx, total, cap)
161
+ return :error if total >= cap
162
+
163
+ share = warn_share(ctx)
164
+ share && total >= share * cap ? :warn : :ok
165
+ end
166
+
167
+ # "$10" for a whole amount, else money's "$7.50".
168
+ def round_money(value) = money(value).delete_suffix(".00")
169
+
170
+ # An amount as /cap reads it: 10, 7.5, 0.006.
171
+ def amount_text(value) = value == value.round ? value.round.to_s : value.round(6).to_s
172
+
124
173
  def check_known(ctx)
125
174
  resolved = resolve(ctx)
126
175
  return unless resolved[:cap]
@@ -291,6 +340,8 @@ class Plugin
291
340
  replaced(ctx, path) if replacing
292
341
  cap = self.class.amount(data["cap"])
293
342
  @mutex.synchronize { @resolved = { session: session, cap: cap, step: self.class.amount(data["step"]) || cap } }
343
+ # /cap, /cap off and Continue: no generation follows them to update it.
344
+ show_chip(ctx)
294
345
  end
295
346
 
296
347
  # Whether +path+ is there but doesn't read (not JSON, or not a mapping).
@@ -1,10 +1,10 @@
1
1
  ---
2
2
  name: dev
3
- version: 0.7.13
3
+ version: 0.7.14
4
4
  scope: system
5
5
  description: "Developer tools"
6
6
  trust_level: reviewed
7
- requires_chi: ">= 0.195.0"
7
+ requires_chi: ">= 0.196.0"
8
8
  includes:
9
9
  - known-names
10
10
  - mcp
@@ -1,10 +1,10 @@
1
1
  ---
2
2
  name: github-pr
3
- version: 0.6.5
3
+ version: 0.6.6
4
4
  scope: system
5
5
  description: Proposes the branch's open GitHub pull request to a session, attached once you mention it (#N, the branch or its URL), and attaches any PR URL with chi context add or the web's "+ URL"; the agent gets a note when reviews, comments, checks or its state change; in the web, a path:line in an answer links to that line of the PR; the auto_attach setting can attach the PR at once instead, or do nothing
6
6
  trust_level: reviewed
7
- requires_chi: ">= 0.150.0"
7
+ requires_chi: ">= 0.196.0"
8
8
  needs:
9
9
  - command: gh
10
10
  why: reads the pull request
@@ -20,5 +20,7 @@ context_providers:
20
20
  cmd: '{ruby} {bundle_dir}/scripts/pr_context.rb {url}'
21
21
  why: GitHub PR
22
22
  every_seconds: 300
23
+ # Two or more of its PRs are one chip in the web's session bar, labelled so.
24
+ context_group: PRs
23
25
  # config.yml bundles: github-pr: (another key warns; an older chi ignores this)
24
26
  settings: [auto_attach, line_links]
@@ -3,8 +3,9 @@
3
3
  # The knowledge bundle's chi-data adapters (manifest.yml plugin: parts:),
4
4
  # the opt-in sources `knowledge_add kind: chi` adds (docs/bundles.md):
5
5
  # SessionsAdapter this project's saved sessions (ctx.sessions.list, read):
6
- # one item per session, its user and model text only (no
7
- # tool output, thinking or notes), chunked by message so a
6
+ # one item per session, the owner's and the model's text
7
+ # only (ctx.speaker: no participant's turn, tool output,
8
+ # thinking or notes), chunked by message so a
8
9
  # hit points at its message (s:<id>#<message>, read with
9
10
  # knowledge_search open:). Incremental: only the sessions
10
11
  # written since the last listing are read; a deleted or
@@ -23,17 +24,24 @@ class Plugin
23
24
  # A session written within this many seconds before the last listing
24
25
  # began is listed again (mtimes are whole seconds).
25
26
  SLACK = 2
26
- # What a hit's chunk says a message was.
27
- SPEAKERS = { "user" => "you", "model" => "model" }.freeze
28
- # The user's own lines: a prompt (no kind) or a mid-turn line.
27
+ # What a hit's chunk says a message was, by its ctx.speaker.
28
+ SPEAKERS = { owner: "you", model: "model" }.freeze
29
+ # The owner's own lines: a prompt (no kind) or a mid-turn line.
29
30
  USER_KINDS = [nil, "input"].freeze
31
+ # The rule an item was indexed by, its sig's prefix ("2:<updated_at>"):
32
+ # an index with a sig of another rule lists its sessions in full again
33
+ # (Plugin#adapter_for), so a session indexed before a participant's
34
+ # turns were dropped is read again.
35
+ RULE = "2"
30
36
  # Secrets by shape and by name, the session's folder kept as it is.
31
37
  VIEWER = Samagotchi::Redact::Viewer.new(cwd: nil)
32
38
 
33
39
  # @param sessions [#list, #present_ids, #read] ctx.sessions
34
40
  # @param listed_at [Integer, nil] when the last listing began (epoch)
35
- def initialize(sessions, listed_at: nil)
41
+ # @param speaker [#call] who wrote a message (ctx.speaker)
42
+ def initialize(sessions, speaker:, listed_at: nil)
36
43
  @sessions = sessions
44
+ @speaker = speaker
37
45
  @since = listed_at && Time.at(listed_at.to_i - SLACK)
38
46
  end
39
47
 
@@ -46,7 +54,7 @@ class Plugin
46
54
  @sessions.list(changed_since: @since).filter_map do |row|
47
55
  updated = Time.iso8601(row[:updated_at].to_s).to_i
48
56
  title = SessionsAdapter.redact(row[:title].to_s).gsub(/\s+/, " ").strip[0, 80]
49
- Item.new(key: row[:id], sig: row[:updated_at].to_s, title: "session #{title.empty? ? row[:id][0, 8] : title}",
57
+ Item.new(key: row[:id], sig: "#{RULE}:#{row[:updated_at]}", title: "session #{title.empty? ? row[:id][0, 8] : title}",
50
58
  ptr: "s:#{row[:id]}", url: nil, path: nil, updated_at: updated)
51
59
  rescue ArgumentError
52
60
  nil
@@ -58,25 +66,37 @@ class Plugin
58
66
 
59
67
  def text(_item) = nil
60
68
 
69
+ # Whether +sig+ was indexed by this RULE.
70
+ def self.current?(sig) = sig.to_s.start_with?("#{RULE}:")
71
+
61
72
  # +text+ as valid UTF-8 with its secrets redacted.
62
73
  def self.redact(text) = Samagotchi::Redact.text(text.dup.force_encoding(Encoding::UTF_8).scrub(""), VIEWER)
63
74
 
64
- # The session's user and model messages, as chunks of at most
75
+ # The session's owner and model messages, as chunks of at most
65
76
  # Chunker::MAX chars, each one's line the index of the message it
66
77
  # starts at (ctx.sessions.read's messages); nil when it can't be read.
78
+ # A participant's turn goes whole, from its opening to the next one:
79
+ # their lines, the model's answers and any line merged into it.
67
80
  def chunks(item)
68
81
  messages = @sessions.read(item.key)[:messages]
69
82
  out = []
70
83
  body = +""
71
84
  start = nil
85
+ participant = false
72
86
  flush = lambda do
73
87
  out << { title: item.title, body: body.strip, line: start } unless body.strip.empty?
74
88
  body = +""
75
89
  end
76
90
  Array(messages).each_with_index do |message, index|
77
- said = said(message) or next
91
+ next unless message.is_a?(Hash)
92
+
93
+ speaker = @speaker.call(message)
94
+ participant = speaker == :participant if opening?(message)
95
+ next if participant
96
+
97
+ said = said(message, speaker) or next
78
98
 
79
- Chunker.pieces("#{SPEAKERS.fetch(message[:role].to_s)}: #{said}\n\n").each do |piece|
99
+ Chunker.pieces("#{SPEAKERS.fetch(speaker)}: #{said}\n\n").each do |piece|
80
100
  flush.call if body.length + piece.length > Chunker::MAX
81
101
  start = index if body.empty?
82
102
  body << piece
@@ -90,12 +110,11 @@ class Plugin
90
110
 
91
111
  private
92
112
 
93
- def said(message)
94
- return nil unless message.is_a?(Hash)
95
-
96
- role = message[:role].to_s
97
- user = role == "user" && USER_KINDS.include?(message[:kind]&.to_s) && message[:source].nil? && !chi_line?(message)
98
- return nil unless user || (role == "model" && message[:kind].nil?)
113
+ # The owner's prompt or mid-turn line, or the model's answer: its text.
114
+ def said(message, speaker)
115
+ kind = message[:kind]&.to_s
116
+ keep = (speaker == :owner && USER_KINDS.include?(kind)) || (speaker == :model && kind.nil?)
117
+ return nil unless keep
99
118
 
100
119
  text = message[:content]
101
120
  return nil unless text.is_a?(String) && !text.strip.empty?
@@ -103,15 +122,14 @@ class Plugin
103
122
  Chunker.clean(text)&.then { |clean| SessionsAdapter.redact(clean).strip }
104
123
  end
105
124
 
106
- # A user message chi wrote, not the user: a `!cmd` line ("!(cmd)\n<its
107
- # output>", no turn_id: Steer.shell_line?'s shape, an env or a .env
108
- # it printed), or /continue no's reason line (an opening_id, no
109
- # turn_id: TurnFlow#abort_continue!, a template around the original
110
- # prompt and the interrupted tools' trace).
111
- def chi_line?(message)
112
- return false if message[:turn_id]
113
-
114
- message[:content].to_s.start_with?("!(") || message[:opening_id].is_a?(String)
125
+ # A turn's first message: one with a turn_id (a prompt, anyone's) or a
126
+ # turn_start one (a wake turn's note or report). Not a kind-less user
127
+ # line without either: a running turn's merged input in a live snapshot
128
+ # (Bridge::TurnAccumulator) has no kind, and a `!cmd` line runs no
129
+ # turn; a participant's turn then runs on over it (dropping more, never
130
+ # less).
131
+ def opening?(message)
132
+ message[:turn_start] == true || !message[:turn_id].nil?
115
133
  end
116
134
  end
117
135
 
@@ -1,25 +1,27 @@
1
1
  ---
2
2
  name: knowledge
3
- version: 0.1.0
3
+ version: 0.1.1
4
4
  scope: system
5
5
  description: "knowledge_search: search a project's docs, memories and the folders, GitHub repos, past sessions and attached context added to its catalog (or a named catalog) in one local SQLite index, each answer saying how old each source is; knowledge_add/list/remove for a kit that adds them (the coordinator kit); /knowledge lists the catalog"
6
6
  trust_level: reviewed
7
7
  plugin:
8
8
  file: plugin.rb
9
- sha256: sha256:9491e3da1663f01f24586343c7bc4802806e504516196aa03b2f550030fa46f5
9
+ sha256: sha256:7be6c875f2fd00f8513eb296c21f8d0dd7dc67a8b0a480faa647b24e4a75565e
10
10
  # Loaded in this order, before plugin.rb.
11
11
  parts:
12
12
  store.rb: sha256:bdc29f55521895d545c706ad3ff2f3778390264bebbcc10cb93b3d354b0f4a33
13
13
  query.rb: sha256:9578ea7392bc6d8a27c5d9b68e47a310b0a8ca937428c80e47b513394d75110f
14
14
  chunker.rb: sha256:169c638ed109ce28e2530868e36b60df7ccffdf64ad64ef027403ba998d7c79e
15
15
  adapters.rb: sha256:11fee1ca0473d9b65a1b66ff50e49b6daf8fdc63d1651e6edc31c02d794ccc1a
16
- chi_adapters.rb: sha256:8c1a98ef7f1fdbcbad186231eef6763d88582f75ea0d79b2fe15a5f72a76e6c1
16
+ chi_adapters.rb: sha256:897ef55c077df1fdab371753f6c0a9fabb5e477a3646ffc96a756b2364266ebb
17
17
  github.rb: sha256:ced3a64d7b03a8b2e724b9d3d8bb8626ffaf66bcdaafd2f2ff41b5888b076a9c
18
18
  catalog.rb: sha256:ffa07afcfb8c3358ac3500bc80f5a028ece79e4adb7e0be5153ef50f95359251
19
19
  refresh.rb: sha256:085545276488772f830757f9f1fe2da9807fb0fdc3a6f1c8851737412ffd3938
20
20
  query_log.rb: sha256:f85602bb073223532ba976189f5bab2ae2a19b98a65c66812d56247dd27e8cfe
21
21
  # chi.tool(declare:) and ctx.project are new: release:bump raises requires_chi.
22
- requires_chi: ">= 0.195.0"
22
+ requires_chi: ">= 0.196.0"
23
+ # ctx.speaker (a participant's turns left out of the sessions source) and
24
+ # chi.tool(participant:) (the catalog tools kept for the owner) are new.
23
25
  needs: [sqlite3, gh, git]
24
26
  # config.yml bundles: knowledge: (another key warns; an older chi ignores this)
25
27
  settings: {refresh_budget_ms: number, max_files: number, sqlite3: string}
@@ -10,8 +10,9 @@
10
10
  # knowledge_add, knowledge_list and knowledge_remove only by a kit that adds
11
11
  # them (declare: :kit: the coordinator kit). /knowledge [catalog] lists a
12
12
  # catalog for the user (owner-only: a participant's / line is refused). A
13
- # participant's turn may only search, and never a
14
- # chi source (memories, sessions, context) nor a named catalog.
13
+ # participant's turn may only search (the catalog tools are participant:
14
+ # :deny: the pair boundary refuses them), and never a chi source
15
+ # (memories, sessions, context) nor a named catalog.
15
16
  #
16
17
  # A source refreshes only when a search (or its own add) finds it older
17
18
  # than its max_age, within refresh_budget_ms (1500); the rest finishes in
@@ -127,7 +128,7 @@ class Plugin
127
128
  } do |args, ctx|
128
129
  args["open"].to_s.strip.empty? ? search(args, ctx) : open_pointer(args, ctx)
129
130
  end
130
- chi.tool ADD, ADD_DESCRIPTION, declare: :kit, label: "adding a knowledge source",
131
+ chi.tool ADD, ADD_DESCRIPTION, declare: :kit, participant: :deny, label: "adding a knowledge source",
131
132
  preview: ->(args) { "#{args["kind"]} #{args["location"]}" },
132
133
  targets: ->(args) { add_targets(args) },
133
134
  params: {
@@ -145,17 +146,17 @@ class Plugin
145
146
  exclude: { type: "array", items: { type: "string" }, description: "Globs to leave out" },
146
147
  catalog: CATALOG_PARAM
147
148
  } do |args, ctx|
148
- owner_only(ctx, ADD) { add(args, ctx) }
149
+ add(args, ctx)
149
150
  end
150
- chi.tool LIST, LIST_DESCRIPTION, declare: :kit, label: "listing knowledge sources",
151
+ chi.tool LIST, LIST_DESCRIPTION, declare: :kit, participant: :deny, label: "listing knowledge sources",
151
152
  params: { kind: { type: "string", description: "Only sources of this kind (folder, github, chi)" },
152
153
  catalog: CATALOG_PARAM } do |args, ctx|
153
- owner_only(ctx, LIST) { list(ctx, catalog: args["catalog"], kind: args["kind"]) }
154
+ list(ctx, catalog: args["catalog"], kind: args["kind"])
154
155
  end
155
- chi.tool REMOVE, REMOVE_DESCRIPTION, declare: :kit, label: "removing a knowledge source",
156
+ chi.tool REMOVE, REMOVE_DESCRIPTION, declare: :kit, participant: :deny, label: "removing a knowledge source",
156
157
  params: { name: { type: "string", required: true, description: "The source's name" },
157
158
  catalog: CATALOG_PARAM } do |args, ctx|
158
- owner_only(ctx, REMOVE) { remove(args, ctx) }
159
+ remove(args, ctx)
159
160
  end
160
161
  chi.on(:before_turn) { |_event, ctx| @mutex.synchronize { @follow_ups.delete(ctx.session_id) } }
161
162
  chi.on(:after_tool_call) { |event, ctx| follow_up(event, ctx) }
@@ -606,12 +607,6 @@ class Plugin
606
607
 
607
608
  # ── catalogs, defaults, refresh ──────────────────────────────────────
608
609
 
609
- def owner_only(ctx, tool)
610
- return "Error: #{tool} is the owner's (a participant's turn can search only)" unless ctx.turn_author.nil?
611
-
612
- yield
613
- end
614
-
615
610
  def catalog_for(ctx, name) = Catalog.locate(data_dir(ctx), project: ctx.project, name: name)
616
611
 
617
612
  # ctx.data_dir realpath'd once (the index's -nofollow refuses a path
@@ -646,9 +641,14 @@ class Plugin
646
641
  when CHI_KIND
647
642
  case source["location"]
648
643
  when "sessions"
649
- # An index that lost its rows (rebuilt, deleted) lists in full again.
650
- indexed = store_for(catalog).then { |store| store.exists? && !store.sigs(source["name"]).empty? }
651
- SessionsAdapter.new(ctx.sessions, listed_at: (source["listed_at"] if indexed))
644
+ # An index that lost its rows (rebuilt, deleted), or holds one of
645
+ # another rule (#sweep deletes those), lists in full again.
646
+ indexed = store_for(catalog).then do |store|
647
+ sigs = store.exists? ? store.sigs(source["name"]) : {}
648
+ !sigs.empty? && sigs.values.all? { |sig| SessionsAdapter.current?(sig) }
649
+ end
650
+ SessionsAdapter.new(ctx.sessions, listed_at: (source["listed_at"] if indexed),
651
+ speaker: ->(message) { ctx.speaker(message) })
652
652
  when "context" then ContextAdapter.new(ctx.context)
653
653
  else MemoriesAdapter.new(source["dirs"].to_h)
654
654
  end
@@ -675,18 +675,37 @@ class Plugin
675
675
 
676
676
  # A deleted, pruned or never-indexable session's rows leave at the next
677
677
  # search that selects a sessions source (ctx.sessions.present_ids:
678
- # file names only), before they can be hits.
678
+ # file names only), before they can be hits; so do the rows an older
679
+ # SessionsAdapter rule indexed (#sweep_old_rule), whatever the source's
680
+ # age, project or the search's budget.
679
681
  def sweep(catalog, store, sources, ctx)
680
682
  names = sources.select { |source| sessions?(source) }.map { |source| source["name"] }
681
683
  return if names.empty? || !store.exists?
682
684
 
683
685
  present = ctx.sessions.present_ids.to_h { |id| [id, true] }
684
686
  names.each do |name|
687
+ sweep_old_rule(catalog, store, name)
685
688
  gone = store.sigs(name).keys.reject { |id| present.key?(id) }
686
689
  catalog.lock { store.delete(gone.map { |id| [name, id] }) } unless gone.empty?
687
690
  end
688
691
  end
689
692
 
693
+ # The sessions source +name+'s rows of an older rule (a sig without
694
+ # RULE's prefix: indexed before a participant's turns were dropped) go,
695
+ # read and deleted under the catalog lock (a refresh's put is too), and
696
+ # its listed_at is cleared: the next listing is a full one, and stays
697
+ # full until one completes.
698
+ def sweep_old_rule(catalog, store, name)
699
+ old = catalog.lock do
700
+ store.sigs(name).reject { |_key, sig| SessionsAdapter.current?(sig) }.keys.tap do |keys|
701
+ store.delete(keys.map { |key| [name, key] }) unless keys.empty?
702
+ end
703
+ end
704
+ return if old.empty?
705
+
706
+ catalog.update { |data| data["sources"].find { |entry| entry["name"] == name }&.delete("listed_at") }
707
+ end
708
+
690
709
  # The searching session's own rows in the sessions sources: never a hit.
691
710
  def own_rows(sources, ctx)
692
711
  id = ctx.session_id
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.195.0
3
+ version: 0.196.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "session"
4
+ require_relative "session_transition"
5
+ require_relative "context_sources"
6
+ require_relative "session_chain/sharing"
7
+
8
+ module Samagotchi
9
+ # A change to a session's own context sources (an add, a remove) under a
10
+ # shared hold of the session's transition lock (SessionChain::Sharing),
11
+ # so a continue (ContextSources.move) can't copy them in between. Its
12
+ # callers: SessionAccess::Local (chi context add / rm) and chi web's URL
13
+ # add and detach. Outside ContextSources, which knows nothing of the lock.
14
+ module ContextChange
15
+ module_function
16
+
17
+ # The block under the hold. A session whose file is gone takes no hold
18
+ # (its folder is not made again).
19
+ # @param state_dir [String] the sessions dir
20
+ # @raise [ContextSources::Held] a transition holds it now (nothing
21
+ # written): Busy's words, or, for a continue (or an older chi's holder
22
+ # that names no kind) with a new link, that link named
23
+ def under(session_id, state_dir:)
24
+ return yield unless Session.exist?(session_id, state_dir: state_dir)
25
+
26
+ SessionChain::Sharing.under(session_id, state_dir: state_dir) do |sharing|
27
+ next yield if sharing.nil?
28
+
29
+ raise ContextSources::Held, refusal(sharing)
30
+ end
31
+ end
32
+
33
+ # The words for a held lock, as the inbox names its link: a delete, a
34
+ # stop or an archive names nobody (Busy's words); a continue's new link
35
+ # in flight "try again in a moment", a saved one "change it there".
36
+ def refusal(sharing)
37
+ if sharing.is_a?(SessionChain::Sharing::Held) || SessionTransition.other_than_continue?(sharing.kind)
38
+ return sharing.busy.message
39
+ end
40
+
41
+ "#{sharing.refusal.message}#{sharing.in_flight? ? "; try again in a moment" : ": change it there"}"
42
+ end
43
+ end
44
+ end
@@ -18,7 +18,7 @@ module Samagotchi
18
18
  # time (MessageTime::KEY) is every entry's, kept beside these.
19
19
  # objectives: the list an objectives note carries (Objectives), string
20
20
  # keys inside. peer: whose answer a peer's note is (ContextAbsorber
21
- # #peer_note: name, re, summary, serial, verdict, agreed), string keys
21
+ # #peer_note: name, re, summary, serial, verdict, said, agreed), string keys
22
22
  # inside; the content doesn't carry it.
23
23
  KEYS = %i[kind note_id source from_session from_cwd context_source objectives peer].freeze
24
24
  HEADER = "CONTEXT NOTE"
@@ -108,6 +108,20 @@ module Samagotchi
108
108
  end
109
109
  end
110
110
 
111
+ # The label the web's session bar folds +bundle+'s sources under
112
+ # (context_group: in its kept manifest), nil when it has none, isn't
113
+ # installed, doesn't read or this chi is too old for it. One record read.
114
+ # @param bundle [String, nil] a source's provider
115
+ # @return [String, nil]
116
+ def group_label(bundle)
117
+ return nil if bundle.nil? || bundle.to_s.empty?
118
+
119
+ standing = InstalledBundles.standing(bundle.to_s)
120
+ return nil if standing.nil? || standing.unreadable? || standing.too_new?
121
+
122
+ standing.record.manifest.context_group
123
+ end
124
+
111
125
  # A bundle this chi is too old for (the verdict's :too_new) has no usable
112
126
  # providers: skip it, and say so once per process per bundle and version,
113
127
  # only when it declares some.
@@ -53,9 +53,9 @@ module Samagotchi
53
53
  class Invalid < ArgumentError; end
54
54
 
55
55
  # A change to a session's own sources refused while a transition holds
56
- # the session's lock (#changing): a continue copies them to its new
57
- # link, so one written then would stay behind. Its words name the
58
- # continue's new link, or say busy; try again in a moment.
56
+ # the session's lock (ContextChange.under): a continue copies them to
57
+ # its new link, so one written then would stay behind. Its words name
58
+ # who continues the session, or say who holds it.
59
59
  class Held < Invalid; end
60
60
 
61
61
  # A source's definition. +cmd+ nil: pushed only (chi context push).
@@ -603,28 +603,6 @@ module Samagotchi
603
603
  File.join(File.dirname(state_dir || SessionPaths.default_state_dir), DIR)
604
604
  end
605
605
 
606
- # The block (a change to session +session_id+'s own sources: an add, a
607
- # remove) under a shared hold of the session's transition lock
608
- # (SessionTransition.shared), so a continue (ContextSources.move) can't
609
- # copy them in between. A session whose file is gone takes no hold (its
610
- # folder is not made again).
611
- # @param state_dir [String] the sessions dir
612
- # @raise [Held] a transition holds it now (nothing written)
613
- def changing(session_id, state_dir:)
614
- return yield unless Session.exist?(session_id, state_dir: state_dir)
615
-
616
- require_relative "session_transition"
617
- require_relative "session_chain/successor"
618
- SessionTransition.shared(session_id, state_dir: state_dir) do |free|
619
- next yield if free
620
-
621
- successor = SessionChain::Successor.in_flight(session_id, state_dir: state_dir)
622
- raise Held, SessionTransition::Busy.held(session_id, state_dir: state_dir).message unless successor
623
-
624
- raise Held, "#{SessionChain::Continued.for(session_id, successor).message}; try again in a moment"
625
- end
626
- end
627
-
628
606
  def session_location(session_id, state_dir: nil)
629
607
  Location.new(scope: "session", dir: File.join(root(state_dir: state_dir), "sessions", SessionPaths.check_id!(session_id)),
630
608
  key: session_id)
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "time"
3
4
  require_relative "../answer_display"
4
5
  require_relative "../bundle_settings_check"
5
6
  require_relative "../cache_confirm"
@@ -7,6 +8,7 @@ require_relative "../client_id"
7
8
  require_relative "../log"
8
9
  require_relative "../plugin/context"
9
10
  require_relative "../plugin/loader"
11
+ require_relative "../session_chips"
10
12
  require_relative "../session_setup"
11
13
 
12
14
  module Samagotchi
@@ -176,6 +178,7 @@ module Samagotchi
176
178
  end,
177
179
  state_dir: -> { session_state_dir },
178
180
  secrets_store: ->(bundle) { Plugin::Secrets::FileStore.for_bundle(bundle) },
181
+ chips: -> { plugin_chips_store },
179
182
  sign_in: ->(bundle, **options, &build) { start_sign_in(bundle: bundle, build: build, **options) },
180
183
  scratch: -> { @scratch },
181
184
  setup: -> { SessionSetup.of(@session, forked: true) },
@@ -195,6 +198,24 @@ module Samagotchi
195
198
  )
196
199
  end
197
200
 
201
+ # The session's chip store ctx.chips writes through (SessionChips),
202
+ # nil with no session; a change announces :chips_updated.
203
+ def plugin_chips_store
204
+ id = @session&.id or return nil
205
+
206
+ SessionChips.new(id, state_dir: session_state_dir, on_change: -> { announce_chips(id) })
207
+ end
208
+ private :plugin_chips_store
209
+
210
+ # :chips_updated (no chips in it: an open tab reads GET …/context
211
+ # again), after a bundle's chip change was written. Under the event
212
+ # lock; the write itself is outside it.
213
+ def announce_chips(session_id)
214
+ synchronize_events { announce(type: :chips_updated, session_id: session_id, at: Time.now.utc.iso8601(3)) }
215
+ rescue StandardError => e
216
+ Log.warn(:plugins, "chips_announce_failed", error: e.class.name, msg: e.message)
217
+ end
218
+
198
219
  # The controller a plugin's ctx.http call without cancel: stops with
199
220
  # (docs/plugins.md): an init task's own, else the running turn's for the
200
221
  # turn's own work until the turn has ended (TurnState#own_controller); nil
@@ -36,6 +36,7 @@ module Samagotchi
36
36
  before_tool_call: :internal,
37
37
  before_turn: :internal,
38
38
  card: :row,
39
+ chips_updated: :state, # A bundle's chips changed (ctx.chips): an open tab reads GET …/context again.
39
40
  command_queued: :state,
40
41
  command_ran: :state,
41
42
  context_added: :row, # Reloaded from the session messages, not a turn fold or card store.
@@ -42,7 +42,11 @@ module Samagotchi
42
42
  # list_schedules, context_read); and memory_write: a memory reaches
43
43
  # the owner's later sessions;
44
44
  # - ask_user_question: there is no one on the participant's side to
45
- # answer it here; the model asks in its reply instead.
45
+ # answer it here; the model asks in its reply instead;
46
+ # - a plugin tool its bundle declared chi.tool(participant: :deny)
47
+ # (Targets#participant: by name, and through call_tool, which
48
+ # ToolIndex#unwrap renames to it before the gate): before its path
49
+ # and command checks and before UNTARGETED's ask.
46
50
  # And it asks the owner, always (Verdict#fresh_ask: no stored approval
47
51
  # answers it, and the rules can't lower it), before a write or an edit
48
52
  # that may land outside the session's project root, or a command that
@@ -66,7 +70,8 @@ module Samagotchi
66
70
  # :ask denied (ASK)
67
71
  # :checked goes on to the path and command checks below
68
72
  # A name not here (a plugin's or an MCP server's tool) goes on to them
69
- # too, but a delegate_* one (OWNER_VOICED_PREFIX). call_tool isn't
73
+ # too, but a delegate_* one (OWNER_VOICED_PREFIX), and a plugin tool
74
+ # declared participant: :deny, refused as BUNDLE_OWNER. call_tool isn't
70
75
  # here: ToolIndex#unwrap renames call_tool(chi/list_sessions) to
71
76
  # list_sessions before the guardrails see it.
72
77
  TOOL_CLASSES = {
@@ -96,10 +101,12 @@ module Samagotchi
96
101
  ASK = "a participant's turn can't ask the user: ask in your reply"
97
102
  OWNER_READS = "a participant's turn can't use %s: the owner's other sessions, reminders, schedules and " \
98
103
  "attached context are the owner's to read"
99
- # A denied kind of TOOL_CLASSES → its refusal (one with %s names the
104
+ BUNDLE_OWNER = "a participant's turn can't use %s: its bundle keeps it for the owner"
105
+ # A denied kind of TOOL_CLASSES (and :bundle_owner, a plugin tool
106
+ # declared participant: :deny) → its refusal (one with %s names the
100
107
  # tool).
101
108
  KIND_TEXTS = { owner_voiced: OWNER_ONLY, owner_tasks: OWNER_TASKS, owner_reader: OWNER_READS,
102
- memory_write: MEMORY_WRITE, ask: ASK }.freeze
109
+ memory_write: MEMORY_WRITE, ask: ASK, bundle_owner: BUNDLE_OWNER }.freeze
103
110
  OUTSIDE_WRITE = "a participant's turn writes outside the session's project"
104
111
  NO_PROJECT = "a participant's turn writes, and this session's folder is the home folder or above it (or none): " \
105
112
  "there is no project to keep it in"
@@ -217,6 +224,7 @@ module Samagotchi
217
224
  call = verdict.call || {}
218
225
  tool = call[:name].to_s
219
226
  kind = TOOL_CLASSES.fetch(tool) { :owner_voiced if tool.start_with?(OWNER_VOICED_PREFIX) }
227
+ kind ||= :bundle_owner if verdict.targets&.participant == :deny
220
228
  if (text = KIND_TEXTS[kind])
221
229
  return text.include?("%s") ? format(text, tool) : text
222
230
  end