samagotchi 0.179.0 → 0.181.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 (95) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +76 -1
  3. data/bin/chi +10 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/bundles.md +39 -3
  6. data/docs/cli.md +16 -9
  7. data/docs/configuration.md +25 -5
  8. data/docs/context.md +7 -0
  9. data/docs/internals/anthropic.md +4 -3
  10. data/docs/internals/background-tasks.md +4 -1
  11. data/docs/internals/block-renderers.md +11 -7
  12. data/docs/internals/bundles.md +12 -10
  13. data/docs/internals/objectives.md +9 -4
  14. data/docs/internals/web-frontend.md +127 -6
  15. data/docs/internals/working-set.md +24 -5
  16. data/docs/memory.md +3 -0
  17. data/docs/plugins.md +17 -6
  18. data/docs/sessions.md +1 -1
  19. data/docs/testing.md +5 -1
  20. data/lib/samagotchi/block_renderers.rb +22 -3
  21. data/lib/samagotchi/bundle_command.rb +9 -2
  22. data/lib/samagotchi/bundle_needs.rb +1 -1
  23. data/lib/samagotchi/bundle_settings_check.rb +5 -2
  24. data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
  25. data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
  26. data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
  27. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  28. data/lib/samagotchi/client.rb +8 -1
  29. data/lib/samagotchi/config.rb +6 -1
  30. data/lib/samagotchi/context_providers.rb +6 -8
  31. data/lib/samagotchi/core_notice.rb +44 -0
  32. data/lib/samagotchi/host_address.rb +7 -0
  33. data/lib/samagotchi/host_config.rb +8 -5
  34. data/lib/samagotchi/host_registry.rb +26 -8
  35. data/lib/samagotchi/installed_bundles/dir.rb +17 -55
  36. data/lib/samagotchi/installed_bundles/standing.rb +23 -3
  37. data/lib/samagotchi/installed_bundles.rb +26 -11
  38. data/lib/samagotchi/kernel_loop.rb +3 -2
  39. data/lib/samagotchi/llm/adapter_common.rb +3 -2
  40. data/lib/samagotchi/llm/adapters.rb +2 -1
  41. data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
  42. data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
  43. data/lib/samagotchi/llm/chat_loop.rb +6 -5
  44. data/lib/samagotchi/llm/errors.rb +41 -3
  45. data/lib/samagotchi/llm/http.rb +85 -22
  46. data/lib/samagotchi/llm/openai_chat.rb +20 -3
  47. data/lib/samagotchi/memory_bundle/status.rb +10 -6
  48. data/lib/samagotchi/objectives.rb +7 -2
  49. data/lib/samagotchi/owner_lock.rb +2 -0
  50. data/lib/samagotchi/plugin/api.rb +4 -1
  51. data/lib/samagotchi/plugin/context.rb +9 -0
  52. data/lib/samagotchi/plugin/peer.rb +32 -15
  53. data/lib/samagotchi/plugin/tool_spec.rb +13 -2
  54. data/lib/samagotchi/row_refs.rb +14 -3
  55. data/lib/samagotchi/session_chain/delete.rb +6 -6
  56. data/lib/samagotchi/session_config.rb +15 -9
  57. data/lib/samagotchi/session_manager/removal.rb +2 -2
  58. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  59. data/lib/samagotchi/terminal_ui/formatting.rb +13 -3
  60. data/lib/samagotchi/terminal_ui/join_replay.rb +1 -1
  61. data/lib/samagotchi/tool_ids.rb +19 -0
  62. data/lib/samagotchi/tool_runner.rb +8 -4
  63. data/lib/samagotchi/tools/registry.rb +3 -2
  64. data/lib/samagotchi/tools/task_runtime.rb +46 -3
  65. data/lib/samagotchi/turn_stages/objectives.rb +10 -5
  66. data/lib/samagotchi/version.rb +1 -1
  67. data/lib/samagotchi/web/public/app.js +22 -14
  68. data/lib/samagotchi/web/public/block_host.js +20 -20
  69. data/lib/samagotchi/web/public/block_renderers.css +5 -5
  70. data/lib/samagotchi/web/public/context_chips.js +183 -49
  71. data/lib/samagotchi/web/public/history_shape.js +5 -3
  72. data/lib/samagotchi/web/public/images.js +1 -1
  73. data/lib/samagotchi/web/public/index.html +90 -5
  74. data/lib/samagotchi/web/public/objectives_strip.js +16 -6
  75. data/lib/samagotchi/web/public/pan_zoom.js +121 -0
  76. data/lib/samagotchi/web/public/peer_chip.js +171 -0
  77. data/lib/samagotchi/web/public/peer_data.js +131 -0
  78. data/lib/samagotchi/web/public/peer_exchange.js +83 -0
  79. data/lib/samagotchi/web/public/peer_links.js +161 -0
  80. data/lib/samagotchi/web/public/peer_note.js +49 -0
  81. data/lib/samagotchi/web/public/picture_viewer.js +304 -0
  82. data/lib/samagotchi/web/public/popover_modal.js +3 -2
  83. data/lib/samagotchi/web/public/session_view.js +10 -1
  84. data/lib/samagotchi/web/public/stream_handlers.js +17 -4
  85. data/lib/samagotchi/web/public/turn_html.js +11 -2
  86. data/lib/samagotchi/web/public/working_set.js +9 -3
  87. data/lib/samagotchi/web/public/working_set_view.js +28 -11
  88. data/lib/samagotchi/web/public/ws_cards.js +36 -10
  89. data/lib/samagotchi/web/public/ws_markdown.js +129 -0
  90. data/lib/samagotchi/web/public/ws_order.js +48 -0
  91. data/lib/samagotchi/web/public/ws_peek.js +22 -5
  92. data/lib/samagotchi/web/public/ws_preview.css +41 -1
  93. data/lib/samagotchi/web/public/ws_reader.js +35 -6
  94. data/lib/samagotchi/web/public/ws_sections.js +24 -15
  95. metadata +11 -1
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "json"
4
4
  require_relative "../tools/args"
5
+ require_relative "../row_refs"
5
6
 
6
7
  module Samagotchi
7
8
  module Plugin
@@ -137,7 +138,8 @@ module Samagotchi
137
138
 
138
139
  # Registry#register's keywords for it: its block wrapped as a handler
139
140
  # (typed args, the Context), preview, targets (in the entry's form,
140
- # (call, surface): a plugin's reads the call only), refs (call only).
141
+ # (call, surface): a plugin's reads the call only), refs ((call,
142
+ # tool_id): a plugin's two-arg refs: lambda gets the run's id too).
141
143
  def entry_fields(context)
142
144
  block = self.block
143
145
  parameters = schema[:parameters]
@@ -151,7 +153,7 @@ module Samagotchi
151
153
  },
152
154
  preview: preview && ->(call, _surface = nil) { preview.call(call)&.to_s },
153
155
  targets: targets && ->(call, _surface = nil) { targets.call(call) },
154
- refs: per_call(refs, parameters)
156
+ refs: refs_per_call(parameters)
155
157
  }
156
158
  end
157
159
 
@@ -163,6 +165,15 @@ module Samagotchi
163
165
  def per_call(fn, parameters)
164
166
  fn && ->(call) { fn.call(ToolSpec.args_of(call, parameters)) }
165
167
  end
168
+
169
+ # The refs: lambda as (call, tool_id) → refs: one that takes two args
170
+ # (args, tool_id) gets the run's id (ToolIds, nil when the run has
171
+ # none), the one its handler reads as ctx.tool_id; a one-arg one the
172
+ # args only (RowRefs.call_with_id).
173
+ def refs_per_call(parameters)
174
+ fn = refs
175
+ fn && ->(call, tool_id = nil) { RowRefs.call_with_id(fn, ToolSpec.args_of(call, parameters), tool_id) }
176
+ end
166
177
  end
167
178
  end
168
179
  end
@@ -27,17 +27,20 @@ module Samagotchi
27
27
  module_function
28
28
 
29
29
  # Runs +fn+ (the tool's refs: lambda, as ToolSpec#per_call wraps it: call →
30
- # a list of {kind:, target:, label:, actions:}) on +call+. Never
30
+ # a list of {kind:, target:, label:, actions:}) on +call+, and on
31
+ # +tool_id+ too when it takes two args (#call_with_id). Never
31
32
  # raises: a lambda that raises or returns something other than a list
32
33
  # gives none, and a bad ref is dropped; both are logged (warn, not
33
34
  # echoed: the turn's live region is on screen).
34
35
  # @param cwd [String, nil] the session's folder
36
+ # @param tool_id [String, nil] the run's id (ToolIds), the one its
37
+ # handler reads (ToolIds.current, a plugin's ctx.tool_id)
35
38
  # @return [Array<Hash>] Ref#to_h each, deduped, at most MAX_REFS
36
- def for(fn, call, cwd:)
39
+ def for(fn, call, cwd:, tool_id: nil)
37
40
  return [] unless fn
38
41
 
39
42
  tool = call[:name].to_s
40
- raw = fn.call(call)
43
+ raw = call_with_id(fn, call, tool_id)
41
44
  return [] if raw.nil?
42
45
  raise ArgumentError, "refs: returned #{raw.class}, not a list" unless raw.is_a?(Array)
43
46
 
@@ -47,6 +50,14 @@ module Samagotchi
47
50
  []
48
51
  end
49
52
 
53
+ # +fn+ on +first+, and on +tool_id+ too when it takes two args (arity
54
+ # 2, or one required and more optional): a one-arg lambda is called as
55
+ # before. ToolSpec's refs: wrapper and #for share it.
56
+ def call_with_id(fn, first, tool_id)
57
+ arity = fn.respond_to?(:arity) ? fn.arity : fn.method(:call).arity
58
+ arity >= 2 || arity <= -2 ? fn.call(first, tool_id) : fn.call(first)
59
+ end
60
+
50
61
  # Stored refs (+raw+, a saved tool_refs entry), each rebuilt and
51
62
  # checked again as #for checks a lambda's: a stored file is never
52
63
  # trusted. What isn't valid any more is dropped, a relative path too
@@ -280,11 +280,11 @@ module Samagotchi
280
280
  end
281
281
  end
282
282
 
283
- # The block under the owner lock (kind deleting, taken without
284
- # waiting) of every id with a folder, the starting marker read again
285
- # under each, held until the block returns: a worker that holds one,
286
- # or a start claimed meanwhile, refuses before anything goes, and
287
- # none takes one midway.
283
+ # The block under the owner lock (kind deleting, with a brief
284
+ # probe-sized wait) of every id with a folder, the starting marker
285
+ # read again under each, held until the block returns: a worker that
286
+ # holds one, or a start claimed meanwhile, refuses before anything
287
+ # goes, and none takes one midway.
288
288
  # @raise [SessionManager::DeleteRefused] :worker_running
289
289
  def locked(ids, state_dir)
290
290
  locks = []
@@ -292,7 +292,7 @@ module Samagotchi
292
292
  dir = Session.session_dir(sid, state_dir: state_dir)
293
293
  next unless Dir.exist?(dir)
294
294
 
295
- lock = OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: 0)
295
+ lock = OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: OwnerLock::PROBE_WAIT)
296
296
  raise SessionManager::DeleteRefused.new(sid, :worker_running) unless lock
297
297
 
298
298
  locks << lock
@@ -213,6 +213,9 @@ module Samagotchi
213
213
  def no_installed_bundle(bundle) = "no installed bundle #{bundle}"
214
214
  def takes_keys(bundle, keys) = keys.empty? ? "#{bundle} takes no settings" : "#{bundle} takes #{keys.join(", ")}"
215
215
  def wrong_type(bundle, key, what, value) = "#{bundle} takes #{what} for #{key}, not #{value.inspect}"
216
+ # A bundle the verdict refuses as a whole (InstalledBundles::Standing:
217
+ # requires_chi), +reason+ its refusal's text.
218
+ def unusable(bundle, reason) = "#{bundle} is installed but this chi can't use it: #{reason}"
216
219
 
217
220
  # --set's values parsed and checked (.parse, .check!) against the
218
221
  # installed bundles (.availability).
@@ -288,9 +291,10 @@ module Samagotchi
288
291
  def offered(dir: nil) = availability(dir: dir).offered
289
292
 
290
293
  # The installed bundles a session may set settings of: a record that
291
- # doesn't read is left out, and so is one whose plugin doesn't load, as
292
- # the verdict says for the loader (InstalledBundles::Standing: requires_chi;
293
- # Dir#file_refusal(:plugin): the file, its sha256), with a note saying why. A record with no
294
+ # doesn't read is left out, and so is one this chi is too old for
295
+ # (InstalledBundles::Standing: requires_chi, plugin or not) or whose
296
+ # plugin doesn't load (Dir#file_refusal(:plugin): the file, its sha256),
297
+ # with a note saying why. A record with no
294
298
  # session_settings whose shipped bundle lists some (installed before
295
299
  # them) gets a note on refreshing it.
296
300
  # @return [Availability]
@@ -306,6 +310,10 @@ module Samagotchi
306
310
 
307
311
  name = standing.name
308
312
  bundle = standing.record
313
+ if standing.too_new?
314
+ notes[name] = unusable(name, standing.refusal.text)
315
+ next
316
+ end
309
317
  if (reason = unloadable(dir, standing))
310
318
  notes[name] = "#{name} is installed but its plugin doesn't load: #{reason}"
311
319
  next
@@ -376,16 +384,14 @@ module Samagotchi
376
384
  "setting#{"s" unless clashing.size == 1} (--set #{clashing.first}=… sets chi's); rename the setting or the bundle"
377
385
  end
378
386
 
379
- # Why +standing+'s plugin doesn't load, as the plugin loader would refuse
380
- # it (InstalledBundles' verdict), nil when it does or it has none. A bundle
381
- # with no plugin is never refused here, even one too new (the plan's D2).
387
+ # Why a usable +standing+'s plugin doesn't load, as the plugin loader
388
+ # would refuse it (Dir#file_refusal(:plugin)), nil when it does or it has
389
+ # none.
382
390
  def unloadable(dir, standing)
383
391
  plugin = standing.record.plugin
384
392
  return nil unless plugin
385
393
 
386
- refusal = standing.refusal ||
387
- InstalledBundles::Dir.new(name: standing.name, dir: dir).file_refusal(:plugin, plugin.file, plugin.sha256)
388
- refusal&.text
394
+ InstalledBundles::Dir.new(name: standing.name, dir: dir).file_refusal(:plugin, plugin.file, plugin.sha256)&.text
389
395
  end
390
396
 
391
397
  # Whether chi ships a bundle +name+ whose manifest lists session_settings.
@@ -426,7 +426,7 @@ module Samagotchi
426
426
  # worker takes the session in the middle; the starting marker is read
427
427
  # again under it (a resume that claimed the start since the caller's
428
428
  # check keeps the session; one after it sees the lock held). Taken
429
- # without waiting: one that took it since the check keeps the session.
429
+ # briefly, so a worker that took it since the check keeps the session.
430
430
  # The lock file goes with the directory; a worker starting after that
431
431
  # makes a new one, and finds no session (Session.load). The delete and
432
432
  # the retention sweep and failed-continue cleanup use #remove_files.
@@ -443,7 +443,7 @@ module Samagotchi
443
443
  # refused after another of the batch went).
444
444
  def remove_session_files(id, path, dir, state_dir:, still: nil, locked: false,
445
445
  running_tasks: RunningTasks::Policy::IGNORE)
446
- lock = !locked && Dir.exist?(dir) ? OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: 0) : nil
446
+ lock = !locked && Dir.exist?(dir) ? OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: OwnerLock::PROBE_WAIT) : nil
447
447
  raise DeleteRefused.new(id, :worker_running) if !locked && Dir.exist?(dir) && lock.nil?
448
448
  raise DeleteRefused.new(id, :worker_running) if StartingMarker.fresh?(id, state_dir: state_dir)
449
449
  raise DeleteRefused.new(id, :changed) if still && !still.call
@@ -324,7 +324,7 @@ module Samagotchi
324
324
  # line in the scrollback; the notes slot is for question choices.
325
325
  when :context_added
326
326
  mark_activity
327
- @screen.commit(context_note_line(event[:label], event[:text]))
327
+ @screen.commit(context_note_line(event[:label], event[:text], event[:peer]))
328
328
  when :continue_offered then offer_continue(event)
329
329
  when :continue_resolved then continue_resolved(event)
330
330
  # The note comes with the kernel's :pending_input_merged (EventRenderer),
@@ -325,8 +325,18 @@ module Samagotchi
325
325
 
326
326
  CONTEXT_NOTE_PREVIEW = 60
327
327
 
328
- # "note from slack: <first line>", cut to one line.
329
- def context_note_line(label, text)
328
+ # "note from slack: <first line>", cut to one line. A peer's answer
329
+ # (+peer+, the note's peer hash) reads "Claude answered · <summary>".
330
+ def context_note_line(label, text, peer = nil)
331
+ peer = peer.transform_keys(&:to_s) if peer.is_a?(Hash)
332
+ summary = peer && peer["summary"].to_s.strip.split("\n").first.to_s
333
+ who = peer && (peer["label"] || peer["peer"]).to_s.strip
334
+ return context_note_preview("#{who} answered \u00b7 ", summary) if summary && !summary.empty? && !who.empty?
335
+
336
+ context_note_preview("note from #{label || "?"}: ", text)
337
+ end
338
+
339
+ def context_note_preview(prefix, text)
330
340
  lines = text.to_s.strip.split("\n")
331
341
  first = lines.first.to_s
332
342
  if first.length > CONTEXT_NOTE_PREVIEW
@@ -334,7 +344,7 @@ module Samagotchi
334
344
  elsif lines.size > 1
335
345
  first += " \u2026"
336
346
  end
337
- paint("note from #{label || "?"}: #{first}", 2)
347
+ paint("#{prefix}#{first}", 2)
338
348
  end
339
349
 
340
350
  # A tool call from the snapshot: it has no action text, only the tool.
@@ -209,7 +209,7 @@ module Samagotchi
209
209
  return if after_exchange != !from.nil?
210
210
 
211
211
  messages[(from ? from + 1 : 0)..].select { |m| ContextNote.note?(m) }.each do |m|
212
- @screen.commit(context_note_line(ContextNote.label_of(m), ContextNote.text_of(m)))
212
+ @screen.commit(context_note_line(ContextNote.label_of(m), ContextNote.text_of(m), ContextNote.fetch(m, :peer)))
213
213
  end
214
214
  end
215
215
 
@@ -34,6 +34,10 @@ module Samagotchi
34
34
  module ToolIds
35
35
  PATTERN = /\At(\d+)\z/
36
36
  DERIVED_PREFIX = "e"
37
+ # Thread.current key: the id of the run whose tool handler runs on
38
+ # this thread (ToolRunner#dispatch, #with_current), what a plugin's
39
+ # handler reads as ctx.tool_id.
40
+ CURRENT = :samagotchi_current_tool_id
37
41
 
38
42
  # One run's id in an entry: the id, the run's position (0-based) and
39
43
  # whether it was derived.
@@ -43,6 +47,21 @@ module Samagotchi
43
47
 
44
48
  module_function
45
49
 
50
+ # The id of the run whose handler runs on this thread (#with_current),
51
+ # nil outside one: another thread, a run with no id.
52
+ # @return [String, nil]
53
+ def current = Thread.current[CURRENT]
54
+
55
+ # Run +block+ with #current as +id+ (nil too), the previous one back
56
+ # after it.
57
+ def with_current(id)
58
+ previous = Thread.current[CURRENT]
59
+ Thread.current[CURRENT] = id
60
+ yield
61
+ ensure
62
+ Thread.current[CURRENT] = previous
63
+ end
64
+
46
65
  # +count+ ids for runs about to go on +conversation+.
47
66
  # @return [Array<String>]
48
67
  def next_ids(conversation, count)
@@ -3,6 +3,7 @@
3
3
  require_relative "tool_activity"
4
4
  require_relative "tool_row_fields"
5
5
  require_relative "row_refs"
6
+ require_relative "tool_ids"
6
7
  require_relative "file_ref"
7
8
  require_relative "guardrails"
8
9
  require_relative "vision_context"
@@ -123,7 +124,8 @@ module Samagotchi
123
124
  # plugin tool's refs); the worker runs in its session's working
124
125
  # directory.
125
126
  fields = ToolRowFields.for(call[:name], call, cwd: Dir.pwd)
126
- refs = RowRefs.for(tools && !call[:name].nil? ? tools[call[:name]]&.refs : nil, call, cwd: session_cwd(context))
127
+ refs = RowRefs.for(tools && !call[:name].nil? ? tools[call[:name]]&.refs : nil, call, cwd: session_cwd(context),
128
+ tool_id: tool_id)
127
129
  fields[:refs] = refs unless refs.empty?
128
130
  started.merge!(fields)
129
131
  # The row's clock: tool_call_completed's duration_ms runs from here.
@@ -147,7 +149,7 @@ module Samagotchi
147
149
  result = denied(call, verdict, context)
148
150
  else
149
151
  dispatched_at = @clock.call
150
- result = dispatch(call, context)
152
+ result = dispatch(call, context, tool_id)
151
153
  elapsed_ms = ((@clock.call - dispatched_at) * 1000).round
152
154
  end
153
155
  diff = file_change(call, before)
@@ -594,8 +596,10 @@ module Samagotchi
594
596
 
595
597
  # KernelLoop#dispatch turns tool errors into "[name] Error: …" itself;
596
598
  # this rescue only catches a failing dispatcher.
597
- def dispatch(call, context)
598
- @kernel.dispatch_tool_call(call, context)
599
+ # The handler runs on this thread with +tool_id+ as ToolIds.current (a
600
+ # plugin's ctx.tool_id), the id its row's refs got too.
601
+ def dispatch(call, context, tool_id = nil)
602
+ ToolIds.with_current(tool_id) { @kernel.dispatch_tool_call(call, context) }
599
603
  rescue StandardError => e
600
604
  { output: "[#{call[:name]}] Error: #{e.class}: #{e.message}", activity: nil }
601
605
  end
@@ -32,8 +32,9 @@ module Samagotchi
32
32
  # @!attribute targets [#call, nil] (call, surface) → what guardrail
33
33
  # rules match. #register takes a one-argument preview or targets
34
34
  # (call only, a plugin's) and gives it this form (.per_call)
35
- # @!attribute refs [#call, nil] call → the row's refs (a plugin's
36
- # refs:, RowRefs checks what it gives)
35
+ # @!attribute refs [#call, nil] call (and the run's tool id, when it
36
+ # takes two args: RowRefs.call_with_id) → the row's refs (a
37
+ # plugin's refs:, RowRefs checks what it gives)
37
38
  # @!attribute source [String] "core", or the bundle that added it
38
39
  # @!attribute layer [Symbol, nil] the LLM context layer the tool
39
40
  # belongs to (LLMContextStrategy): offered only in a turn running
@@ -2,10 +2,13 @@
2
2
 
3
3
  require "fileutils"
4
4
  require "json"
5
+ require "open3"
6
+ require "pathname"
5
7
  require "securerandom"
6
8
  require "shellwords"
7
9
  require "time"
8
10
  require_relative "../atomic_file"
11
+ require_relative "../git_env"
9
12
  require_relative "../log"
10
13
  require_relative "../process_group"
11
14
  require_relative "../spawn_env"
@@ -77,6 +80,7 @@ module Samagotchi
77
80
  exit_code_path = File.expand_path(File.join(task_dir, TaskFiles::EXIT_CODE_FILENAME))
78
81
 
79
82
  FileUtils.mkdir_p(task_dir)
83
+ exclude_task_dir
80
84
 
81
85
  # The child writes to it; the ensure below closes the parent's copy.
82
86
  output_io = File.open(output_path, "a") # rubocop:disable Style/FileOpen
@@ -242,8 +246,8 @@ module Samagotchi
242
246
  def settle_pending!(timeout:)
243
247
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
244
248
  threads = @waiters_lock.synchronize do
245
- @waiters.values.filter_map do |thread, _pid, detach|
246
- thread if thread != Thread.current && thread.alive? && (!detach.alive? || thread[SETTLING])
249
+ @waiters.values.filter_map do |thread, pid, detach|
250
+ thread if thread != Thread.current && thread.alive? && shell_reaped?(thread, pid, detach)
247
251
  end
248
252
  end
249
253
  threads.each { |thread| thread.join([deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max) }
@@ -252,6 +256,15 @@ module Samagotchi
252
256
  alive
253
257
  end
254
258
 
259
+ # Whether a waiter's shell is reaped: its detach thread ended, the
260
+ # waiter is past the reap (SETTLING), or the pid is gone. Right after
261
+ # Process.detach reaps the shell its thread still runs a moment and
262
+ # SETTLING isn't set yet; kill(0) reads ESRCH only after the reap
263
+ # (a zombie answers), and a reused pid reads alive and is skipped.
264
+ def shell_reaped?(thread, pid, detach)
265
+ !detach.alive? || thread[SETTLING] || (ProcessGroup.signalable?(pid) && !ProcessGroup.alive?(pid))
266
+ end
267
+
255
268
  # Joins every live EXIT_STATUS_THREAD, for up to +timeout+ s in all: a
256
269
  # spec calls it (with_task_dir) after stopping its tasks and before it
257
270
  # removes their folder, which a recorder may still write into. chi
@@ -318,6 +331,7 @@ module Samagotchi
318
331
  record = task.with(command: task.command.to_s.strip, cwd: File.expand_path(cwd.to_s.empty? ? Dir.pwd : cwd),
319
332
  pid_started: ProcessGroup.start_time(pid), handed_over_by: ToolNames::Execute::NAME)
320
333
  write_record(record)
334
+ exclude_task_dir
321
335
  [record, nil]
322
336
  rescue StandardError => e
323
337
  [nil, "Error: #{e.message}"]
@@ -526,6 +540,35 @@ module Samagotchi
526
540
  FileUtils.mkdir_p(TaskFiles.tasks_dir)
527
541
  end
528
542
 
543
+ def exclude_task_dir
544
+ dir = File.realpath(TaskFiles.root || Dir.pwd)
545
+ out, err, status = Open3.capture3(GitEnv::UNSET, "git", "-C", dir, "rev-parse",
546
+ "--show-toplevel", "--git-common-dir")
547
+ unless status.success?
548
+ Log.warn(:turn, "task_exclude_failed", msg: err.strip) unless err.include?("not a git repository")
549
+ return
550
+ end
551
+
552
+ root, common = out.lines.map(&:chomp)
553
+ relative = Pathname.new(dir).relative_path_from(Pathname.new(File.realpath(root))).to_s
554
+ path = relative == "." ? TaskFiles::TASKS_DIR : File.join(relative, TaskFiles::TASKS_DIR)
555
+ raise ArgumentError, "task path contains a newline" if path.match?(/[\r\n]/)
556
+
557
+ pattern = "/#{path.gsub(/([\\*?\[\]])/, '\\\\\1')}/"
558
+ exclude = File.join(File.expand_path(common, dir), "info", "exclude")
559
+ FileUtils.mkdir_p(File.dirname(exclude))
560
+ File.open(exclude, File::RDWR | File::CREAT, 0o666) do |file|
561
+ file.flock(File::LOCK_EX)
562
+ contents = file.read
563
+ next if contents.lines.any? { |line| line.chomp == pattern }
564
+
565
+ file.write("\n") unless contents.empty? || contents.end_with?("\n")
566
+ file.write("#{pattern}\n")
567
+ end
568
+ rescue StandardError => e
569
+ Log.warn(:turn, "task_exclude_failed", error: e.class.name, msg: e.message)
570
+ end
571
+
529
572
  def generate_task_id
530
573
  loop do
531
574
  candidate = "#{Time.now.utc.strftime("%Y%m%d%H%M%S")}-#{SecureRandom.hex(4)}"
@@ -612,7 +655,7 @@ module Samagotchi
612
655
  :status_code, :correct_finished_record, :record_at,
613
656
  :leftover_group?, :settle_from_refresh, :chis_group?, :mark_not_chis, :not_found,
614
657
  :record_json, :ensure_tasks_dir, :normalize_cwd, :mark_finished_without_exit_code, :finished_with, :current_record,
615
- :mark_stopped, :read_exit_code, :timestamp
658
+ :mark_stopped, :read_exit_code, :timestamp, :shell_reaped?
616
659
  end
617
660
  end
618
661
  end
@@ -100,16 +100,21 @@ module Samagotchi
100
100
  # The session's objectives as the page draws them (Engine#objectives_view),
101
101
  # when that differs from the last announced: after an edit (its file
102
102
  # written, pending), once a list note is in, at a turn's end (its moves)
103
- # and after a rollback. A session with no list announces nothing. The caller
104
- # (Engine#announce_objectives) holds the event lock, the one guard of
105
- # the last view, announces the event and logs a failure: it only
106
- # informs, never fails a turn.
103
+ # and after a rollback. A list going away (a rollback or a turn's kept
104
+ # messages past its note) announces once, without items, so the page
105
+ # clears; a session with no list before and after announces nothing.
106
+ # The caller (Engine#announce_objectives) holds the event lock, the one
107
+ # guard of the last view, announces the event and logs a failure: it
108
+ # only informs, never fails a turn.
107
109
  # @param view [Hash, nil] the view from Engine#objectives_view
108
110
  # @return [Hash, nil] the :objectives_updated event to announce, nil when the view is the same
109
111
  def announce(session, view:)
110
- return if view.nil? || view == @announced
112
+ return if view == @announced
111
113
 
112
114
  @announced = view
115
+ # Written out: **nil raises on Ruby 3.3.
116
+ return { type: :objectives_updated, session_id: session.id, items: nil } if view.nil?
117
+
113
118
  { type: :objectives_updated, session_id: session.id, **view }
114
119
  end
115
120
 
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.179.0"
4
+ VERSION = "0.181.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -131,7 +131,11 @@ import { createMarkdownTip } from "./markdown_tip.js";
131
131
  import { IMAGES_NOT_HERE } from "./images.js";
132
132
  import { withoutStaleParams } from "./stale_params.js";
133
133
  import { createViewer } from "./viewer.js";
134
+ import { createPictureViewer, thumbPicture } from "./picture_viewer.js";
134
135
  import { createParticipantMain } from "./participant_main.js";
136
+ import { createPeers } from "./peer_data.js";
137
+ import { peerStatusCommand } from "./peer_chip.js";
138
+ import { createPeerLinks } from "./peer_links.js";
135
139
  import { PARTICIPANT_REVISE_UNAVAILABLE, participantMayRevise, participantReviseUnavailable } from "./participant_revise.js";
136
140
 
137
141
  // A link's #code= (behind an auth proxy): traded for the cookie before
@@ -151,6 +155,7 @@ onAuthLost(authLost);
151
155
  const $ = (s) => document.querySelector(s);
152
156
  // Who looks and what they may do (viewer.js): every owner-only control and call asks it.
153
157
  const viewer = createViewer(document.body);
158
+ const pictures = createPictureViewer({ el: $("#lightbox") }); // a picture over the page (picture_viewer.js)
154
159
  const topStripEl = $("#topStrip");
155
160
  const allListEl = $("#allList");
156
161
  const historyEl = $("#history");
@@ -170,6 +175,10 @@ const contextChips = viewer.can("context") ? createContextChips({
170
175
  el: $("#contextChips"),
171
176
  api: { list: listContext, show: getContext, detach: detachContext },
172
177
  toast: (text) => showToast(text),
178
+ // A paired peer's one chip (peer_chip.js): its exchanges are the peers model's (below).
179
+ peers: () => peers,
180
+ peerActions: { status: (name) => peerStatusCommand(store.current.commands, name), run: (line) => runSessionCommand(line),
181
+ drawn: (id) => peerLinks.hasSend(id), jump: (id) => peerLinks.showSend(id) },
173
182
  }) : null;
174
183
  // The open session's ⚙ chip in the info bar, and its panel (thinking,
175
184
  // reasoning history, LLM context): a pick runs its command in the session's
@@ -351,7 +360,7 @@ const { renderMarkdown, pairRefsIn, linkRefsIn, applyFinalMarkdown } = markdownP
351
360
  const wsLine = viewer.can("session_controls") ? (line) => (store.selected ? sendCommand(store.selected, line, { clientId }) : null) : null;
352
361
  // What chi has of an item (the owner's): the rows' peek and the reader over the stage (ws_reader.js).
353
362
  const wsPreview = document.body.dataset.workingSet === "1" && viewer.can("working_set_items")
354
- ? createWorkingSetPreview({ centerEl: $("#center"), session: () => store.selected, state: () => store.current, sendLine: wsLine }) : null;
363
+ ? createWorkingSetPreview({ centerEl: $("#center"), session: () => store.selected, state: () => store.current, sendLine: wsLine, renderMarkdown }) : null;
355
364
  const workingSet = document.body.dataset.workingSet === "1" && viewer.can("working_set")
356
365
  ? createWorkingSet({
357
366
  historyEl, stageRoot: () => turnDom.root, state: () => store.current, session: () => store.selected, infoEl: infoTextEl,
@@ -427,6 +436,10 @@ if (viewer.can("answer_cards")) turnRoots().forEach((root) => root.addEventListe
427
436
  function findInTurnRoots(selector) {
428
437
  return turnRoots().flatMap((root) => [...root.querySelectorAll(selector)]);
429
438
  }
439
+ // The open session's peers (peer_data.js, owner only) and their exchange drawn in the conversation (peer_links.js).
440
+ const peers = contextChips ? createPeers({ sessionId: () => store.selected, onChange: () => { peerLinks.draw(); contextChips.peersChanged(); },
441
+ hasPeer: () => peerLinks.hasPeer() || contextChips.rows.some((row) => row.peer) }) : null;
442
+ const peerLinks = peers && createPeerLinks({ peers, roots: turnRoots, running: () => liveTurn.running, showText: (name) => contextChips.showText?.(name) });
430
443
  // The running turn as the page follows it (live_turn.js): whether one
431
444
  // runs, its timing line and the turns this page saw end (live_timing.js),
432
445
  // its merges' bubble flags, its turn-end reads.
@@ -536,7 +549,7 @@ turnRoots().forEach((root) => root.addEventListener("click", cards.onCardAction)
536
549
  const sessionView = createSessionView({
537
550
  store, historyEl, getSession,
538
551
  liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet, wsPreview, gapClock,
539
- bubbles, cards, markdown: markdownPlace, cardRegistry,
552
+ bubbles, cards, markdown: markdownPlace, cardRegistry, peerLinks, pictures,
540
553
  capabilities: () => pageCapabilities,
541
554
  page: {
542
555
  setReviseAnchor, renderInitRow, setMarkdownWarning, setCapabilities, findInTurnRoots, appendToHistory,
@@ -836,7 +849,7 @@ function applyView() {
836
849
  // Its chip was in the list just hidden (the strip, or all sessions).
837
850
  lists.chainPop.close();
838
851
  if (open) {
839
- lists.familyPop.close(); // the strip is hidden in the all view
852
+ lists.familyPop.close(); pictures.close(); // the strip and #center (the picture viewer's parent) are hidden there
840
853
  // The list is live; only its order can lag (upserts keep cards in
841
854
  // place), so the all view opens in the server's order.
842
855
  // A new list: the lists' redraw draws the all view (lists.render).
@@ -1170,6 +1183,7 @@ const streamHandlers = observeCards(cardRegistry, (participant ? participant.wra
1170
1183
  shownTexts,
1171
1184
  questionCards,
1172
1185
  contextChips,
1186
+ peers,
1173
1187
  workingSet,
1174
1188
  participantsControl,
1175
1189
  placeVerdict: ownerVerify.placeVerdict,
@@ -1346,7 +1360,6 @@ viewer.control($("#newBtn"), "sessions")?.addEventListener("click", () => {
1346
1360
  startPage.loadModels({ asked: true });
1347
1361
  });
1348
1362
 
1349
- const lightboxEl = $("#lightbox");
1350
1363
 
1351
1364
  // The empty box: one line in a session, three on the start page.
1352
1365
  function promptMinPx() {
@@ -1382,7 +1395,7 @@ const composer = mountComposer({
1382
1395
  session: () => store.selected,
1383
1396
  waiting: sessionWaits,
1384
1397
  allViewOpen,
1385
- lightboxOpen: () => !lightboxEl.hidden,
1398
+ lightboxOpen: () => pictures.isOpen(),
1386
1399
  },
1387
1400
  });
1388
1401
  // Bound here, not hoisted: no top-level code above this line may call them.
@@ -1415,17 +1428,11 @@ const unqueue = createUnqueue({
1415
1428
  return true;
1416
1429
  },
1417
1430
  });
1418
- turnRoots().forEach((root) => root.addEventListener("click", (e) => { unqueue.onClick(e); }));
1419
1431
  turnRoots().forEach((root) => root.addEventListener("click", (e) => {
1432
+ unqueue.onClick(e);
1420
1433
  const img = e.target.closest("img.thumb");
1421
- if (!img) return;
1422
- lightboxEl.querySelector("img").src = img.src;
1423
- lightboxEl.hidden = false;
1434
+ if (img) pictures.open(thumbPicture(img));
1424
1435
  }));
1425
- lightboxEl.addEventListener("click", () => { lightboxEl.hidden = true; });
1426
- document.addEventListener("keydown", (e) => {
1427
- if (e.key === "Escape" && !lightboxEl.hidden) lightboxEl.hidden = true;
1428
- });
1429
1436
 
1430
1437
  // The / autocomplete (command_list.js): the session's commands while the
1431
1438
  // composer holds one "/word".
@@ -1536,7 +1543,8 @@ turnRoots().forEach((root) => installCopy(root));
1536
1543
  // chi-ui blocks (inline_widgets.js) are a core drawer, ahead of the bundles'
1537
1544
  // renderers; a picks' Fill reply only fills the composer.
1538
1545
  const widgets = createWidgetDrawer({ roots: turnRoots(), composerText: () => promptEl.value, fillComposer });
1539
- createBlockHost({ roots: turnRoots(), sessionId: () => store.selected, drawers: [widgets], renderers: viewer.can("block_renderers") });
1546
+ createBlockHost({ roots: turnRoots(), sessionId: () => store.selected, drawers: [widgets], renderers: viewer.can("block_renderers"), openPicture: (p, o) => pictures.open(p, o) });
1547
+ window.matchMedia?.("(prefers-color-scheme: dark)").addEventListener?.("change", () => pictures.close()); // a redrawn diagram's old picture
1540
1548
  // A steps block, a thinking block and the recap open and close by hand
1541
1549
  // with their height animated (details_motion.js), in the history and on
1542
1550
  // the stage.