samagotchi 0.88.0 → 0.90.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.
@@ -0,0 +1,159 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "open3"
5
+ require "rbconfig"
6
+ require "tmpdir"
7
+ require "yaml"
8
+ require_relative "../../config"
9
+ require_relative "../../cli/exit"
10
+ require_relative "../../installed_gem"
11
+ require_relative "../../memory_bundle"
12
+ require_relative "../../memory_bundle/shas"
13
+ require_relative "../../session_manager"
14
+
15
+ module Samagotchi
16
+ class BundleCommand
17
+ module Try
18
+ class Sandbox
19
+ LIB_DIR = File.expand_path("../../..", __dir__)
20
+ CHI = File.expand_path("../../../../bin/chi", __dir__)
21
+ SHIPPED_DIR = MemoryBundle::SourceNormalizer::SHIPPED_DIR
22
+ CONFIG_DENYLIST = %w[
23
+ bundles hooks guardrails memories append_system_prompt recap session log web update kitty tmux broadcast
24
+ context_sources
25
+ ].freeze
26
+ CONFIG_DENYLIST_ENV_PREFIXES = CONFIG_DENYLIST.map do |section|
27
+ prefix = if section == "guardrails"
28
+ SessionManager::GUARDRAILS_ENV_PREFIX.delete_suffix("_")
29
+ else
30
+ "SAMAGOTCHI_#{section.upcase}"
31
+ end
32
+ prefix
33
+ end.freeze
34
+ class Error < StandardError
35
+ attr_reader :status
36
+
37
+ def initialize(message, status: CLI::Exit::FAILED)
38
+ super(message)
39
+ @status = status
40
+ end
41
+ end
42
+
43
+ attr_reader :root, :config_home, :state_home, :work_dir, :manifest
44
+
45
+ def initialize(path, bundle_settings: {}, cost_cap: 1, cost_cap_override: false)
46
+ @path = File.realpath(path)
47
+ @bundle_settings = bundle_settings
48
+ @cost_cap = cost_cap
49
+ @cost_cap_override = cost_cap_override
50
+ read_manifest
51
+ @root = File.realpath(Dir.mktmpdir("chi-bundle-try-"))
52
+ @config_home = File.join(root, "config")
53
+ @state_home = File.join(root, "state")
54
+ @work_dir = File.join(root, "work")
55
+ [config_home, state_home, work_dir].each { |dir| FileUtils.mkdir_p(dir) }
56
+ @work_dir = File.realpath(@work_dir)
57
+ write_config
58
+ @child_env = build_child_env
59
+ rescue StandardError
60
+ cleanup
61
+ raise
62
+ end
63
+
64
+ def child_env = @child_env.dup
65
+
66
+ def install
67
+ install_path(@path)
68
+ %w[guardrails cost-cap].each do |name|
69
+ next if @manifest.name == name
70
+
71
+ install_path(File.join(SHIPPED_DIR, name))
72
+ end
73
+ @manifest
74
+ end
75
+
76
+ def cleanup
77
+ FileUtils.rm_rf(root) if root && File.exist?(root)
78
+ end
79
+
80
+ private
81
+
82
+ def write_config
83
+ source = ConfigFile.read_yaml(env: ENV.to_h) || {}
84
+ data = source.to_h { |key, value| [key.to_s, value] }
85
+ # Drop bundles, hooks, guardrails, memories, append_system_prompt,
86
+ # recap, session, log, web, update, kitty, tmux, broadcast and
87
+ # context sources; keep model and ordinary runtime settings.
88
+ CONFIG_DENYLIST.each { |key| data.delete(key) }
89
+ data["context"] = data["context"].dup if data["context"].is_a?(Hash)
90
+ data["context"]&.delete("sources")
91
+ data["bundles"] = { "cost-cap" => { "cap" => @cost_cap } }
92
+ data["bundles"][@manifest.name] ||= {}
93
+ data["bundles"][@manifest.name].merge!(@bundle_settings)
94
+ data["bundles"]["cost-cap"]["cap"] = @cost_cap if @cost_cap_override
95
+ path = File.join(config_home, "samagotchi", "config.yml")
96
+ FileUtils.mkdir_p(File.dirname(path))
97
+ File.write(path, YAML.dump(data))
98
+ end
99
+
100
+ def read_manifest
101
+ file = File.join(@path, "manifest.yml")
102
+ raise Error.new("chi bundle try: not a bundle: #{@path} (chi bundle new NAME)", status: CLI::Exit::USAGE) unless File.file?(file)
103
+
104
+ text = File.read(file)
105
+ stale = MemoryBundle::Shas.stale(@path, text)
106
+ unless stale.empty?
107
+ raise Error, "chi bundle try: stale or placeholder sha256 in manifest.yml; run chi bundle check --fix"
108
+ end
109
+
110
+ @manifest = MemoryBundle::Manifest.read(dir: @path)
111
+ if @manifest.meta?
112
+ raise Error.new("chi bundle try: profile bundles cannot be tried directly", status: CLI::Exit::USAGE)
113
+ end
114
+
115
+ @manifest
116
+ rescue MemoryBundle::Manifest::ValidationError => e
117
+ raise Error, "chi bundle try: #{e.message}"
118
+ rescue MemoryBundle::Shas::Error => e
119
+ raise Error, "chi bundle try: #{e.message}"
120
+ rescue Psych::Exception => e
121
+ raise Error, "chi bundle try: manifest.yml is not valid YAML (#{e.message})"
122
+ end
123
+
124
+ def install_path(path)
125
+ out, err, status = Open3.capture3(child_env, RbConfig.ruby, "-I", LIB_DIR, CHI,
126
+ "bundle", "install", path, "--force", chdir: work_dir)
127
+ return if status.success?
128
+
129
+ message = [out, err].reject(&:empty?).join("\n").strip
130
+ raise Error, "chi bundle try: #{message.empty? ? "bundle install failed" : message}"
131
+ end
132
+
133
+ def build_child_env
134
+ env = ENV.to_h
135
+ SessionManager::SESSION_MARKER_ENV.each { |key| env.delete(key) }
136
+ env.delete("SAMAGOTCHI_LOG_FILE")
137
+ env.delete("SAMAGOTCHI_LOG_DISABLE")
138
+ env.delete("SAMAGOTCHI_SKIP_SYSTEM_BUNDLE")
139
+ env.delete("SAMAGOTCHI_ENV") if env["SAMAGOTCHI_ENV"] == "test"
140
+ env.delete("SAMAGOTCHI_INSTALLED_VERSION")
141
+ env.delete_if do |key, _|
142
+ key.start_with?(SessionManager::WORKER_ENV_PREFIX) || key == SessionManager::BOOT_FALLBACK_ENV ||
143
+ CONFIG_DENYLIST_ENV_PREFIXES.any? { |prefix| key == prefix || key.start_with?("#{prefix}_") }
144
+ end
145
+ env.merge!(
146
+ "HOME" => Dir.home,
147
+ "SAMAGOTCHI_KEYCHAIN" => "on",
148
+ "XDG_CONFIG_HOME" => config_home,
149
+ "XDG_STATE_HOME" => state_home,
150
+ "SAMAGOTCHI_RECAP_ENABLED" => "false",
151
+ "SAMAGOTCHI_CACHE_WARMUP" => "off"
152
+ )
153
+ env.merge!(InstalledGem.unbundled_env_changes(env)) if InstalledGem.spec
154
+ env
155
+ end
156
+ end
157
+ end
158
+ end
159
+ end
@@ -0,0 +1,152 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../../analytics_file"
5
+ require_relative "../../session_metrics"
6
+
7
+ module Samagotchi
8
+ class BundleCommand
9
+ module Try
10
+ Trace = Data.define(
11
+ :session_id, :exit_code, :answer, :tools, :notices, :cards, :questions, :denied,
12
+ :interactive_blocked, :used_memories, :tokens, :cost, :cost_is_estimate, :model, :sandbox, :stderr_tail
13
+ )
14
+
15
+ class TraceReader
16
+ DENIAL_TEXT = "No one to approve it (non-interactive run)."
17
+ SESSION_ID = /\A[A-Za-z0-9_-]+\z/
18
+ STDERR_LIMIT = 4000
19
+
20
+ def initialize(state_home:, session_id:)
21
+ @state_home = state_home
22
+ @session_id = session_id if session_id.to_s.match?(SESSION_ID)
23
+ end
24
+
25
+ def read(exit_code:, answer:, stderr:, sandbox:)
26
+ return empty_trace(exit_code, answer, stderr, sandbox) unless @session_id
27
+
28
+ sessions_dir = File.join(@state_home, "samagotchi", "sessions")
29
+ session_path = File.join(sessions_dir, "#{@session_id}.json")
30
+ session_dir = File.join(sessions_dir, @session_id)
31
+ session = json_file(session_path) || {}
32
+ messages = Array(session["messages"]).select { |message| message.is_a?(Hash) }
33
+ analytics = AnalyticsFile.read(session_dir) || {}
34
+ entries = card_entries(session_dir)
35
+ tool_rows, denied = tools(messages, analytics)
36
+ summary = SessionMetrics.saved_summary(session_dir)
37
+ cost, estimate = cost_summary(summary)
38
+ questions = entries.select { |entry| entry["type"] == "question" }
39
+ notices = entries.select { |entry| entry["type"] == "hook_notice" }
40
+ cards = entries.select { |entry| entry["type"] == "card" }
41
+ blocked_count = questions.count { |question| unanswerable?(question) } + denied.size
42
+
43
+ Trace.new(
44
+ session_id: @session_id, exit_code: exit_code, answer: answer.to_s, tools: tool_rows, notices: notices,
45
+ cards: cards, questions: questions, denied: denied, interactive_blocked: blocked_count.positive?,
46
+ used_memories: Array(session["used_memory_names"]), tokens: {
47
+ prompt: summary&.prompt_sum, completion: summary&.completion_sum
48
+ },
49
+ cost: cost, cost_is_estimate: estimate, model: session["model_name"], sandbox: sandbox,
50
+ stderr_tail: tail(stderr)
51
+ )
52
+ end
53
+
54
+ private
55
+
56
+ def empty_trace(exit_code, answer, stderr, sandbox)
57
+ Trace.new(session_id: nil, exit_code: exit_code, answer: answer.to_s, tools: [], notices: [], cards: [],
58
+ questions: [], denied: [], interactive_blocked: false, used_memories: [], tokens: {
59
+ prompt: nil, completion: nil
60
+ }, cost: nil, cost_is_estimate: false, model: nil, sandbox: sandbox, stderr_tail: tail(stderr))
61
+ end
62
+
63
+ def tools(messages, analytics)
64
+ records = Array(analytics["tool_records"]).select { |record| record.is_a?(Hash) }
65
+ .to_h do |record|
66
+ [[record["iteration"].to_i, record["call_index"].to_i], record]
67
+ end
68
+ tool_responses = messages.select { |message| %w[tool_response tool].include?(message["role"]) }
69
+ denied = []
70
+ index = 0
71
+ iteration = 0
72
+ rows = messages.flat_map do |message|
73
+ next [] unless %w[model assistant].include?(message["role"])
74
+
75
+ iteration += 1
76
+ Array(message["tool_calls"]).each_with_index.filter_map do |call, call_index|
77
+ next unless call.is_a?(Hash)
78
+
79
+ index += 1
80
+ record = records[[iteration, call_index + 1]]
81
+ id = call["id"]
82
+ response = tool_responses.find { |entry| entry["tool_call_id"] == id } if id
83
+ response ||= tool_responses[index - 1] unless id
84
+ is_denied = response && response["content"].to_s.include?(DENIAL_TEXT)
85
+ denied << index if is_denied
86
+ status = is_denied ? "denied" : record&.dig("status").to_s
87
+ status = "unknown" if status.empty?
88
+ {
89
+ index: index,
90
+ name: record&.[]("called_as") || record&.[]("tool") || call_name(call),
91
+ args: argument_text(call),
92
+ status: status,
93
+ duration_ms: record&.[]("duration_ms").to_i
94
+ }
95
+ end
96
+ end
97
+ [rows, denied]
98
+ end
99
+
100
+ def call_name(call)
101
+ function = call["function"].is_a?(Hash) ? call["function"] : {}
102
+ call["name"] || function["name"] || "tool"
103
+ end
104
+
105
+ def argument_text(call)
106
+ function = call["function"].is_a?(Hash) ? call["function"] : {}
107
+ args = call["arguments"] || function["arguments"] || {}
108
+ args = JSON.parse(args) if args.is_a?(String)
109
+ if args.is_a?(Hash)
110
+ preferred = %w[command content path url query].filter_map { |key| args[key] }.first
111
+ args = preferred || JSON.generate(args)
112
+ end
113
+ args.to_s.gsub(/\s+/, " ").strip[0, 200]
114
+ rescue JSON::ParserError
115
+ args.to_s.gsub(/\s+/, " ").strip[0, 200]
116
+ end
117
+
118
+ def card_entries(session_dir)
119
+ data = json_file(File.join(session_dir, "cards.json"))
120
+ entries = data.is_a?(Hash) ? data["entries"] : []
121
+ Array(entries).select { |entry| entry.is_a?(Hash) }
122
+ end
123
+
124
+ def unanswerable?(question)
125
+ question["cancelled"] && question["reason"] == "non_interactive"
126
+ end
127
+
128
+ def cost_summary(summary)
129
+ return [nil, false] unless summary
130
+
131
+ reported = summary.cost_sum.to_f
132
+ estimate = summary.cost_estimate_sum.to_f
133
+ return [reported, false] if reported.positive?
134
+ return [nil, false] unless estimate.positive?
135
+
136
+ [estimate, true]
137
+ end
138
+
139
+ def json_file(path)
140
+ JSON.parse(File.read(path))
141
+ rescue JSON::ParserError, SystemCallError
142
+ nil
143
+ end
144
+
145
+ def tail(text)
146
+ value = text.to_s
147
+ value.length > STDERR_LIMIT ? value[-STDERR_LIMIT, STDERR_LIMIT] : value
148
+ end
149
+ end
150
+ end
151
+ end
152
+ end
@@ -10,7 +10,7 @@ module Samagotchi
10
10
  # subcommands have their own flags).
11
11
  class BundleCommand
12
12
  USAGE = <<~TEXT
13
- Usage: chi bundle <install|upgrade|uninstall|status|diff|list|build|trash|new|test|check> [options]
13
+ Usage: chi bundle <install|upgrade|uninstall|status|diff|list|build|trash|new|test|check|try> [options]
14
14
 
15
15
  install <source> [--scope system|project] [--force]
16
16
  Install a memory bundle from a directory, zip, tar archive, or git URL.
@@ -52,17 +52,26 @@ module Samagotchi
52
52
  check [PATH] [--fix] [--set KEY=VALUE]
53
53
  Check a bundle you're writing (default: the current dir): manifest, files, sha256 lines,
54
54
  requires_chi, and an install + load in a sandbox. --fix rewrites stale sha256 lines.
55
+
56
+ try PATH -p TEXT [options]
57
+ Run one non-interactive model turn with a bundle installed in an isolated sandbox.
55
58
  TEXT
56
59
 
57
60
  # Each subcommand's --help (and only --help: -h and help are taken as
58
61
  # the source or name).
59
62
  INSTALL_HELP = <<~TEXT
60
63
  Usage: chi bundle install <source> [--scope system|project] [--force]
64
+ chi bundle install --dev PATH
61
65
 
62
66
  install <source> [--scope system|project] [--force]
63
67
  Install a memory bundle from a directory, zip, tar archive, or git URL,
64
68
  or a bundle shipped with chi by name (see: chi bundle list).
65
69
  --force overwrites existing entries; default skips them.
70
+ install --dev PATH
71
+ Install the bundle in the local directory PATH as a link to it: its plugin, hooks, rules and scripts
72
+ are PATH's own files (an edit applies at the next worker or chi web restart, with no re-install) and
73
+ their sha256 isn't checked, for this bundle only. Its memories are copied; re-install with --force to
74
+ pick up memory edits. Upgrade refuses it; uninstall removes the link, never PATH's files.
66
75
  TEXT
67
76
  UPGRADE_HELP = "Usage: chi bundle upgrade <source> [--scope system|project] [--force] [--dry-run] [--agent|--no-agent]"
68
77
  UNINSTALL_HELP = "Usage: chi bundle uninstall <bundle> [--scope system|project] [--force]"
@@ -108,6 +117,19 @@ module Samagotchi
108
117
  --set KEY=VALUE a setting for the load (config.yml bundles: <name>: KEY), repeatable
109
118
  Exit status: 0 no errors, 1 errors, 2 usage.
110
119
  TEXT
120
+ TRY_HELP = <<~TEXT
121
+ Usage: chi bundle try PATH -p TEXT [--model NAME] [--memory NAME] [--mute NAME] [--toolkit NAME]
122
+ [--thinking LEVEL] [--set KEY=VALUE] [--json] [--keep] [--timeout SECONDS]
123
+
124
+ Install PATH and run one non-interactive turn in an isolated temporary config, state and work directory.
125
+ The user's hosts, keys and ordinary runtime settings are retained; their bundles, hooks, guardrails,
126
+ memories, prompt additions, sessions and attached context sources are not. Shipped guardrails and a
127
+ $1 cost cap are installed for the run. --set KEY=VALUE sets the tried bundle's config.yml bundles entry;
128
+ --set cost-cap.cap=N overrides the cap (unlike chi --set BUNDLE.KEY=VALUE, these are config settings).
129
+ --memory and --mute accept comma-separated names and repeat. --keep retains the sandbox and debug log.
130
+ --json prints the experimental machine-readable trace.
131
+ Exit status: child turn's status; 1 on install failure or timeout; 2 for usage; 130 on Ctrl-C.
132
+ TEXT
111
133
 
112
134
  # The subcommands' flags: --help only; a word not starting with -- is
113
135
  # a positional (install's source, -h included). --scope takes whatever
@@ -115,8 +137,12 @@ module Samagotchi
115
137
  INSTALL_FLAGS = CLI::Flags.new(help: %w[--help], flag_pattern: /\A--/) do |f|
116
138
  f.value "--scope"
117
139
  f.switch "--force"
140
+ f.switch "--dev"
141
+ end
142
+ UNINSTALL_FLAGS = CLI::Flags.new(help: %w[--help], flag_pattern: /\A--/) do |f|
143
+ f.value "--scope"
144
+ f.switch "--force"
118
145
  end
119
- UNINSTALL_FLAGS = INSTALL_FLAGS
120
146
  UPGRADE_FLAGS = CLI::Flags.new(help: %w[--help], flag_pattern: /\A--/) do |f|
121
147
  f.value "--scope"
122
148
  f.switch "--force"
@@ -135,6 +161,19 @@ module Samagotchi
135
161
  f.switch "--fix"
136
162
  f.value "--set", key: :set, repeat: true
137
163
  end
164
+ TRY_FLAGS = CLI::Flags.new(help: %w[--help], flag_pattern: /\A-/) do |f|
165
+ f.value "-p", "--prompt", key: :prompt
166
+ f.value "--model"
167
+ f.value "--memory", repeat: true
168
+ f.value "--mute", repeat: true
169
+ f.value "--toolkit"
170
+ f.value "--thinking"
171
+ f.value "--set", repeat: true
172
+ f.switch "--json"
173
+ f.switch "--keep"
174
+ f.value "--timeout"
175
+ f.refuse "--attach", "--shared", "chi bundle try can't use --attach or --shared"
176
+ end
138
177
  TRASH_FLAGS = CLI::Flags.new(help: %w[--help], flag_pattern: /\A--/) do |f|
139
178
  f.switch "--empty"
140
179
  f.switch "--dry-run"
@@ -169,8 +208,9 @@ module Samagotchi
169
208
  when "new" then new_bundle(@argv[1..])
170
209
  when "test" then test_bundle(@argv[1..])
171
210
  when "check" then check(@argv[1..])
211
+ when "try" then try_bundle(@argv[1..])
172
212
  else
173
- @stderr.puts "Unknown bundle subcommand: #{sub}. Use: install, upgrade, uninstall, status, diff, list, build, trash, new, test, check"
213
+ @stderr.puts "Unknown bundle subcommand: #{sub}. Use: install, upgrade, uninstall, status, diff, list, build, trash, new, test, check, try"
174
214
  CLI::Exit::USAGE
175
215
  end
176
216
  end
@@ -185,11 +225,21 @@ module Samagotchi
185
225
  source = parsed.args.last
186
226
  scope = opts[:scope]
187
227
  force = opts.fetch(:force, false)
228
+ dev = opts.fetch(:dev, false)
188
229
  if source.nil? || source.empty?
189
230
  @stderr.puts "Usage: chi bundle install <source> [--scope system|project] [--force]"
190
231
  return CLI::Exit::USAGE
191
232
  end
192
- expanded_source = expand_source(source)
233
+ if dev && (Samagotchi::MemoryBundle::SourceNormalizer.git_url?(source) || !File.directory?(source))
234
+ @stderr.puts "chi bundle install --dev takes a local directory (the bundle's source), not #{source}"
235
+ return CLI::Exit::USAGE
236
+ end
237
+ expanded_source = dev ? File.realpath(source) : expand_source(source)
238
+ if dev && File.dirname(expanded_source) == File.realpath(Samagotchi::MemoryBundle::SourceNormalizer::SHIPPED_DIR)
239
+ @stderr.puts "chi bundle install --dev cannot be used with chi-shipped bundles or profiles; " \
240
+ "use chi bundle install #{File.basename(expanded_source)} instead"
241
+ return CLI::Exit::USAGE
242
+ end
193
243
  if Samagotchi::MemoryBundle::Profile.shipped_meta?(expanded_source)
194
244
  return install_profile(expanded_source, scope: scope, force: force, dry_run: false, word: "Install")
195
245
  end
@@ -198,7 +248,7 @@ module Samagotchi
198
248
  return 1 unless prepared
199
249
  return 1 if installed_under_another_name?(expanded_source, bundle_name, prepared, "Install")
200
250
 
201
- installer = installer_for(expanded_source, bundle_name, prepared: prepared, scope: scope, force: force)
251
+ installer = installer_for(expanded_source, bundle_name, prepared: prepared, scope: scope, force: force, dev: dev)
202
252
  run_installer(installer, failed: "Install") do |manifest|
203
253
  print_hooks_and_plugin(manifest)
204
254
  print_provenance(bundle_name, manifest)
@@ -457,7 +507,7 @@ module Samagotchi
457
507
  @stdout.puts "Bundle '#{name}' not installed."
458
508
  return 0
459
509
  end
460
- @stdout.puts "Bundle: #{name} v#{st[:provenance].version} scope=#{status_scope(st)} installed=#{st[:provenance].installed_at}"
510
+ @stdout.puts "Bundle: #{name} v#{st[:provenance].version}#{dev_label(st[:provenance])} scope=#{status_scope(st)} installed=#{st[:provenance].installed_at}"
461
511
  if st[:scope_error]
462
512
  @stdout.puts "Target: (unknown scope: this chi can't resolve it; upgrade chi or reinstall the bundle)"
463
513
  else
@@ -519,12 +569,19 @@ module Samagotchi
519
569
  plugin_info = plugin ? " plugin=#{plugin[:file]}" : ""
520
570
  includes = st[:provenance].includes
521
571
  includes_info = includes ? " includes=#{includes.join(",")}" : ""
522
- @stdout.puts " #{bname} v#{st[:provenance].version} scope=#{status_scope(st)} files=#{st[:files].size}#{hook_info}#{plugin_info}#{includes_info} issues=#{mods}"
572
+ @stdout.puts " #{bname} v#{st[:provenance].version}#{dev_label(st[:provenance])} scope=#{status_scope(st)} files=#{st[:files].size}#{hook_info}#{plugin_info}#{includes_info} issues=#{mods}"
523
573
  end
524
574
  end
525
575
  0
526
576
  end
527
577
 
578
+ # " dev → /path (missing)" when a dev install's source isn't there, else "".
579
+ def dev_label(record)
580
+ return "" unless record.dev
581
+
582
+ " dev → #{record.source}#{" (missing)" unless File.directory?(record.source)}"
583
+ end
584
+
528
585
  # "team (unknown)" for a scope this chi can't resolve (Status#bundle_status).
529
586
  def status_scope(st) = st[:scope_error] ? "#{st[:scope]} (unknown)" : st[:scope]
530
587
 
@@ -844,7 +901,7 @@ module Samagotchi
844
901
  parsed = parse_flags(CHECK_FLAGS, rest, "check", help: CHECK_HELP)
845
902
  return parsed if parsed.is_a?(Integer)
846
903
 
847
- settings = check_settings(parsed.options.fetch(:set, [])) or return CLI::Exit::USAGE
904
+ settings = check_settings(parsed.options.fetch(:set, []), label: "check") or return CLI::Exit::USAGE
848
905
  if parsed.args.size > 1
849
906
  @stderr.puts "chi bundle check takes one PATH (#{parsed.args.join(" ")})"
850
907
  return CLI::Exit::USAGE
@@ -858,14 +915,163 @@ module Samagotchi
858
915
  Check.new(dir, fix: parsed.options.fetch(:fix, false), settings: settings, stdout: @stdout).run
859
916
  end
860
917
 
918
+ def try_bundle(rest)
919
+ parsed = parse_flags(TRY_FLAGS, rest, "try", help: TRY_HELP)
920
+ return parsed if parsed.is_a?(Integer)
921
+
922
+ options = parsed.options
923
+ if options[:prompt].nil? || parsed.args.size != 1
924
+ @stderr.puts "Usage: chi bundle try PATH -p TEXT [options]"
925
+ return CLI::Exit::USAGE
926
+ end
927
+ path = parsed.args.first
928
+ unless File.directory?(path)
929
+ @stderr.puts "chi bundle try: #{path} isn't a folder"
930
+ return CLI::Exit::USAGE
931
+ end
932
+ if options.values_at(:model, :toolkit, :thinking, :memory, :mute).flatten.compact.any?(&:empty?)
933
+ @stderr.puts "chi bundle try: model, toolkit, thinking, memory and mute values cannot be empty"
934
+ return CLI::Exit::USAGE
935
+ end
936
+ require_relative "thinking"
937
+ if options[:thinking] && !Thinking::LEVELS.map(&:to_s).include?(options[:thinking])
938
+ @stderr.puts "chi bundle try: --thinking takes #{Thinking::LEVELS.join(", ")}, not #{options[:thinking]}"
939
+ return CLI::Exit::USAGE
940
+ end
941
+
942
+ timeout = parse_try_timeout(options[:timeout])
943
+ return CLI::Exit::USAGE unless timeout
944
+
945
+ set_pairs = []
946
+ cost_cap = 1
947
+ cost_cap_override = false
948
+ require_relative "bundle_session_settings"
949
+ Array(options[:set]).each do |pair|
950
+ key, sep, value = pair.partition("=")
951
+ if sep.empty?
952
+ @stderr.puts "chi bundle try: --set takes KEY=VALUE, not #{pair}"
953
+ return CLI::Exit::USAGE
954
+ end
955
+ if key == "cost-cap.cap"
956
+ cost_cap = BundleSessionSettings.typed(value)
957
+ cost_cap_override = true
958
+ unless (cost_cap.is_a?(Numeric) && cost_cap >= 0) || cost_cap == false
959
+ @stderr.puts "chi bundle try: --set cost-cap.cap takes a non-negative number or off"
960
+ return CLI::Exit::USAGE
961
+ end
962
+ else
963
+ set_pairs << pair
964
+ end
965
+ end
966
+ settings = check_settings(set_pairs, label: "try")
967
+ return CLI::Exit::USAGE unless settings
968
+
969
+ require_relative "bundle_command/try/sandbox"
970
+ require_relative "bundle_command/try/run"
971
+ require_relative "bundle_command/try/trace"
972
+ sandbox = nil
973
+ begin
974
+ sandbox = Try::Sandbox.new(path, bundle_settings: settings, cost_cap: cost_cap,
975
+ cost_cap_override: cost_cap_override)
976
+ sandbox.install
977
+ result = Try::Run.new(sandbox).run(prompt: options[:prompt], options: options, timeout: timeout)
978
+ trace = Try::TraceReader.new(state_home: sandbox.state_home, session_id: result.session_id)
979
+ .read(exit_code: result.exit_status, answer: result.stdout, stderr: result.stderr,
980
+ sandbox: options[:keep] ? sandbox.root : nil)
981
+ render_try_trace(trace, json: options[:json], child_stderr: result.stderr)
982
+ @stderr.puts "chi bundle try: timed out after #{timeout} seconds" if result.timed_out
983
+ result.exit_status
984
+ rescue Try::Sandbox::Error => e
985
+ @stderr.puts e.message
986
+ e.status
987
+ ensure
988
+ report_try_sandbox(sandbox) if options[:keep] && sandbox
989
+ sandbox&.cleanup unless options[:keep]
990
+ end
991
+ end
992
+
993
+ def render_try_trace(trace, json:, child_stderr:)
994
+ error_lines = child_stderr.lines.reject { |line| line.start_with?("Session: ") }
995
+ @stderr.write(error_lines.join)
996
+ if json
997
+ render_trace_lines(trace, @stderr, include_answer: false)
998
+ @stdout.puts JSON.generate(trace.to_h.transform_keys(&:to_s))
999
+ else
1000
+ render_trace_lines(trace, @stdout, include_answer: true)
1001
+ end
1002
+ end
1003
+
1004
+ def report_try_sandbox(sandbox)
1005
+ @stderr.puts "sandbox: #{sandbox.root}"
1006
+ @stderr.puts "debug log: #{File.join(sandbox.state_home, "samagotchi", "samagotchi.log")}"
1007
+ end
1008
+
1009
+ def render_trace_lines(trace, output, include_answer:)
1010
+ output.puts "tools:"
1011
+ trace.tools.each do |tool|
1012
+ output.puts format(" %d %-16s %-7s %dms %s", tool[:index], tool[:name], tool[:status],
1013
+ tool[:duration_ms], JSON.generate(tool[:args].to_s[0, 60]))
1014
+ end
1015
+ trace.notices.each { |notice| output.puts "notices: [#{notice["hook"] || "hook"}] #{notice["text"]}" }
1016
+ trace.cards.each do |card|
1017
+ output.puts "card: #{[card["title"], card["body"]].compact.join(" — ")}"
1018
+ end
1019
+ trace.questions.each do |entry|
1020
+ question = entry.dig("pending_question", "question").to_s
1021
+ outcome = if entry["cancelled"] && entry["reason"] == "non_interactive"
1022
+ "unanswerable (non_interactive)"
1023
+ elsif entry["cancelled"]
1024
+ "cancelled (#{entry["reason"]})"
1025
+ elsif entry["answer"]
1026
+ "answered"
1027
+ else
1028
+ "unanswered"
1029
+ end
1030
+ output.puts "questions: #{JSON.generate(question)} -> #{outcome}"
1031
+ end
1032
+ if trace.interactive_blocked
1033
+ count = trace.denied.size + trace.questions.count { |question| question["cancelled"] && question["reason"] == "non_interactive" }
1034
+ output.puts "warn: #{count} question(s)/call(s) couldn't be answered"
1035
+ end
1036
+ if include_answer
1037
+ answer_lines = trace.answer.lines
1038
+ output.puts "answer:"
1039
+ answer_lines.first(10).each { |line| output.puts " #{line.chomp}" }
1040
+ output.puts " … (truncated)" if answer_lines.size > 10
1041
+ end
1042
+ tokens = trace.tokens
1043
+ prompt = tokens[:prompt] || "unknown"
1044
+ completion = tokens[:completion] || "unknown"
1045
+ cost = if trace.cost
1046
+ "#{"~" if trace.cost_is_estimate}$#{format("%.4f", trace.cost)}"
1047
+ else
1048
+ "unknown"
1049
+ end
1050
+ output.puts "tokens: #{prompt} in / #{completion} out cost #{cost} exit #{trace.exit_code}" \
1051
+ "#{" (#{trace.session_id})" if trace.session_id}"
1052
+ end
1053
+
1054
+ def parse_try_timeout(value)
1055
+ return 300 unless value
1056
+
1057
+ timeout = Float(value)
1058
+ return timeout if timeout.positive? && timeout.finite?
1059
+
1060
+ @stderr.puts "chi bundle try: --timeout must be a positive number"
1061
+ nil
1062
+ rescue ArgumentError
1063
+ @stderr.puts "chi bundle try: --timeout must be a positive number"
1064
+ nil
1065
+ end
1066
+
861
1067
  # --set KEY=VALUE values as typed (BundleSessionSettings.typed), or nil
862
1068
  # after saying what's wrong.
863
- def check_settings(pairs)
1069
+ def check_settings(pairs, label:)
864
1070
  require_relative "bundle_session_settings"
865
1071
  pairs.each_with_object({}) do |pair, out|
866
1072
  key, sep, value = pair.partition("=")
867
1073
  unless !sep.empty? && key.match?(BundleSessionSettings::KEY)
868
- @stderr.puts "chi bundle check: --set takes KEY=VALUE, not #{pair}"
1074
+ @stderr.puts "chi bundle #{label}: --set takes KEY=VALUE, not #{pair}"
869
1075
  return nil
870
1076
  end
871
1077
  out[key] = BundleSessionSettings.typed(value)
@@ -176,6 +176,8 @@ module Samagotchi
176
176
  file = File.join(dir, name, "plugin", bundle.plugin.file.to_s)
177
177
  return "the file is missing" unless File.file?(file)
178
178
 
179
+ return nil if MemoryBundle::Provenance.unchecked?(bundle.plugin.sha256)
180
+
179
181
  expected = MemoryBundle::Provenance.recorded_sha(bundle.plugin.sha256)
180
182
  return "no sha256 recorded for it (reinstall the bundle)" if expected.empty?
181
183
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.88.0
3
+ version: 0.90.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:
@@ -134,8 +134,7 @@ module Samagotchi
134
134
 
135
135
  record.scripts.each do |file, sha|
136
136
  path = File.join(provenance.scripts_dir, file)
137
- recorded = MemoryBundle::Provenance.recorded_sha(sha)
138
- next if File.file?(path) && MemoryBundle::Provenance.file_sha(path) == recorded
137
+ next if File.file?(path) && MemoryBundle::Provenance.sha_matches?(path, sha)
139
138
 
140
139
  raise Invalid, "bundle #{source.provider}'s scripts/#{file} differs from the installed one (reinstall the bundle)"
141
140
  end