samagotchi 0.189.0 → 0.190.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +35 -1
- data/docs/architecture.md +4 -1
- data/docs/cli.md +17 -6
- data/docs/configuration.md +1 -0
- data/docs/guardrails.md +20 -8
- data/docs/internals/attached-context.md +4 -1
- data/docs/internals/engine.md +18 -2
- data/docs/pages.md +3 -2
- data/docs/scheduling.md +99 -5
- data/docs/sub-agent.md +1 -1
- data/lib/samagotchi/bundles/guardrails/guardrails/rules.yml +15 -0
- data/lib/samagotchi/bundles/guardrails/manifest.yml +2 -2
- data/lib/samagotchi/bundles/schedules/manifest.yml +4 -4
- data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +13 -3
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/config.rb +2 -0
- data/lib/samagotchi/context_fetch.rb +9 -3
- data/lib/samagotchi/engine/models.rb +6 -4
- data/lib/samagotchi/engine/turn_end.rb +20 -2
- data/lib/samagotchi/engine.rb +5 -1
- data/lib/samagotchi/failure_line.rb +43 -0
- data/lib/samagotchi/guardrail_wiring.rb +3 -1
- data/lib/samagotchi/guardrails/chi_dirs.rb +20 -5
- data/lib/samagotchi/guardrails/parent_approvals.rb +1 -1
- data/lib/samagotchi/guardrails/protected_paths.rb +8 -4
- data/lib/samagotchi/guardrails/shell_paths.rb +16 -2
- data/lib/samagotchi/guardrails/targets.rb +1 -1
- data/lib/samagotchi/guardrails/verdict.rb +5 -3
- data/lib/samagotchi/image_store.rb +4 -0
- data/lib/samagotchi/last_turn.rb +2 -1
- data/lib/samagotchi/llm/utf8_scrub.rb +26 -0
- data/lib/samagotchi/llm_context_view.rb +6 -0
- data/lib/samagotchi/model_profile.rb +4 -1
- data/lib/samagotchi/pages/runtime.rb +4 -3
- data/lib/samagotchi/reply_wait.rb +1 -1
- data/lib/samagotchi/schedule_command.rb +99 -5
- data/lib/samagotchi/schedule_display.rb +21 -5
- data/lib/samagotchi/schedules/condition_part.rb +312 -0
- data/lib/samagotchi/schedules/edit_part.rb +27 -3
- data/lib/samagotchi/schedules/notices_part.rb +8 -2
- data/lib/samagotchi/schedules/protection_part.rb +10 -0
- data/lib/samagotchi/schedules/prune_part.rb +79 -0
- data/lib/samagotchi/schedules.rb +57 -82
- data/lib/samagotchi/system_one/self_protect.rb +4 -2
- data/lib/samagotchi/tools/cancel_schedule.rb +27 -2
- data/lib/samagotchi/tools/execute.rb +5 -1
- data/lib/samagotchi/tools/list_schedules.rb +1 -0
- data/lib/samagotchi/tools/task_runtime.rb +6 -0
- data/lib/samagotchi/turn_endings.rb +14 -2
- data/lib/samagotchi/turn_flow.rb +2 -1
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/public/stream_handlers.js +8 -0
- data/lib/samagotchi/web/session_hub.rb +16 -5
- data/lib/samagotchi/worker.rb +6 -4
- metadata +4 -1
|
@@ -16,8 +16,8 @@ module Samagotchi
|
|
|
16
16
|
# @steer_cut, @hooks, @event_log, @client.
|
|
17
17
|
module TurnEndPart
|
|
18
18
|
# How the turn ended, on the session (Session#last_turn): the caller's
|
|
19
|
-
# save puts it in the file the session hub watches
|
|
20
|
-
#
|
|
19
|
+
# save puts it in the file the session hub watches (#end_turn, and
|
|
20
|
+
# #fail_turn_not_begun where no #end_turn ran).
|
|
21
21
|
# @param limit [Integer, nil] the turn ran out of iterations at this
|
|
22
22
|
# limit: "exhausted" => true, "limit" => N, so a wait with nobody to
|
|
23
23
|
# answer the continue offer says so (ReplyWait, ParentReport "limit")
|
|
@@ -32,6 +32,24 @@ module Samagotchi
|
|
|
32
32
|
**stop_facts(event))
|
|
33
33
|
end
|
|
34
34
|
|
|
35
|
+
# A turn that failed before the Engine's began (the Worker's steps
|
|
36
|
+
# before #run_turn raised, or #begin_turn did): idle again, its
|
|
37
|
+
# last_turn and its :turn_failed as an Engine turn's failure has
|
|
38
|
+
# them (TurnEndings#failed_event, the same line), with no
|
|
39
|
+
# :turn_started before it and nothing kept. Observers only (no turn
|
|
40
|
+
# sink); the caller logs it.
|
|
41
|
+
# @param origin [TurnOrigin] the turn's
|
|
42
|
+
# @param turn_id [String, nil] the id the turn would have run under
|
|
43
|
+
def fail_turn_not_begun(session, error, origin:, turn_id: nil)
|
|
44
|
+
synchronize_events do
|
|
45
|
+
event = failed_event(error, 0)
|
|
46
|
+
event[:turn_id] = turn_id if turn_id
|
|
47
|
+
session.status = Session::STATUS_IDLE
|
|
48
|
+
record_last_turn(session, "failed", 0, origin, event)
|
|
49
|
+
emit_event(nil, origin.empty? ? event : event.merge(origin: origin.to_h))
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
35
53
|
# Why a turn stopped (TurnEndings#stop_facts).
|
|
36
54
|
def stop_facts(event) = @turn_endings.stop_facts(event)
|
|
37
55
|
private :stop_facts
|
data/lib/samagotchi/engine.rb
CHANGED
|
@@ -954,7 +954,8 @@ module Samagotchi
|
|
|
954
954
|
# only re-raised: the turn already ended; so is any error there. Any
|
|
955
955
|
# other error (e.g. an LLM::ProviderError) emits :turn_failed and
|
|
956
956
|
# re-raises; a provider error adds error_kind:, retryable:, host: and a
|
|
957
|
-
# one-line summary
|
|
957
|
+
# one-line summary:, chi's own (FailureLine.chi_error?) error_kind:
|
|
958
|
+
# :chi_error and its summary: (logged with its backtrace, chi_error).
|
|
958
959
|
def run_turn(session, prompt, on_event: nil, max_iterations: nil, cancel_controller: nil, max_tool_output_chars: nil, pending_input: nil, continue: false,
|
|
959
960
|
origin: TurnOrigin::NONE, images: [], id: nil, resumed: false, resume_from: nil, verify: nil, revises: nil,
|
|
960
961
|
input_waiting: nil, opener_source: nil, reply_for: nil)
|
|
@@ -997,6 +998,9 @@ module Samagotchi
|
|
|
997
998
|
raise
|
|
998
999
|
end
|
|
999
1000
|
|
|
1001
|
+
# chi's own failure: where it raised goes to the log (its line
|
|
1002
|
+
# says "details in samagotchi.log").
|
|
1003
|
+
Log.exception(:turn, "chi_error", e) if TurnEndings.chi_error?(e)
|
|
1000
1004
|
# Keep what the turn got to (the prompt plus the loop's completed
|
|
1001
1005
|
# tool iterations) like a cancel does, and save it: a worker exits
|
|
1002
1006
|
# after a failed turn.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "llm/errors"
|
|
4
|
+
require_relative "llm/utf8_scrub"
|
|
5
|
+
|
|
6
|
+
module Samagotchi
|
|
7
|
+
# Marks an error whose message tells the user what to change (an image
|
|
8
|
+
# the turn can't use, no model configured): a turn it fails shows that
|
|
9
|
+
# message as it is, never as a chi error (FailureLine.chi_error?).
|
|
10
|
+
module UserError
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
# The one line a failed turn shows (every UI, through the end event's
|
|
14
|
+
# summary: TurnEndings#failed_event) and its note keeps (TurnNote.failed:
|
|
15
|
+
# the reload's line, the model's; TurnFlow#prompt_turn_failed too), and
|
|
16
|
+
# whether chi itself failed. Light on purpose: the TUI's and chi web's
|
|
17
|
+
# thin loads reach it through TurnFlow.
|
|
18
|
+
module FailureLine
|
|
19
|
+
# A failed turn's error_kind when chi itself failed (.chi_error?).
|
|
20
|
+
CHI_ERROR = :chi_error
|
|
21
|
+
# The longest error message a chi error's line quotes.
|
|
22
|
+
MESSAGE_MAX = 300
|
|
23
|
+
|
|
24
|
+
module_function
|
|
25
|
+
|
|
26
|
+
# Whether +error+ is chi's own failure: neither the provider's
|
|
27
|
+
# (LLM::ProviderError, its own kind and summary) nor one that tells the
|
|
28
|
+
# user what to change (UserError).
|
|
29
|
+
def chi_error?(error) = !error.is_a?(LLM::ProviderError) && !error.is_a?(UserError)
|
|
30
|
+
|
|
31
|
+
# A provider error's summary, a UserError's message, else "chi error:
|
|
32
|
+
# <message> (<Class>); details in samagotchi.log". Its first line, read
|
|
33
|
+
# as UTF-8: the message may hold the bytes that failed.
|
|
34
|
+
# @return [String]
|
|
35
|
+
def for(error)
|
|
36
|
+
return error.summary if error.respond_to?(:summary)
|
|
37
|
+
return error.message unless chi_error?(error)
|
|
38
|
+
|
|
39
|
+
message = LLM::Utf8Scrub.call(error.message.to_s).lines.first.to_s.strip[0, MESSAGE_MAX]
|
|
40
|
+
"chi error: #{message} (#{error.class.name}); details in samagotchi.log"
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end
|
|
@@ -273,6 +273,7 @@ module Samagotchi
|
|
|
273
273
|
require_relative "chi_home"
|
|
274
274
|
require_relative "chi_shim"
|
|
275
275
|
require_relative "paths"
|
|
276
|
+
require_relative "guardrails/chi_dirs"
|
|
276
277
|
Guardrails::ProtectedPaths.new(
|
|
277
278
|
store_dir: File.dirname(@approvals.path),
|
|
278
279
|
bundles_dir: InstalledBundles.dir,
|
|
@@ -283,7 +284,8 @@ module Samagotchi
|
|
|
283
284
|
runs_dir: File.join(File.dirname(@approvals.path, 2), "system_one"),
|
|
284
285
|
home_path: ChiHome.path,
|
|
285
286
|
shim_path: ChiShim.path,
|
|
286
|
-
plugins_dir: File.join(Paths.state_dir, "plugins")
|
|
287
|
+
plugins_dir: File.join(Paths.state_dir, "plugins"),
|
|
288
|
+
schedules_path: Guardrails::ChiDirs.schedules_file
|
|
287
289
|
)
|
|
288
290
|
end
|
|
289
291
|
end
|
|
@@ -13,10 +13,12 @@ module Samagotchi
|
|
|
13
13
|
# (read each call). Each surface keeps its set:
|
|
14
14
|
# .protected the config dir, the hooks dir, the approval store's
|
|
15
15
|
# dir, the installed bundles' dir, attached context,
|
|
16
|
-
# the peer mailbox, System 1's saved runs
|
|
16
|
+
# the peer mailbox, System 1's saved runs, and one file,
|
|
17
|
+
# schedules.json: an ask only the user may answer
|
|
17
18
|
# (ParentApprovals.chi_files?)
|
|
18
19
|
# .touches .protected and the session repo's git hooks dir: a
|
|
19
|
-
# rule's touches: chi_dirs (Targets#touches_chi?)
|
|
20
|
+
# rule's touches: chi_dirs (Targets#touches_chi?), with
|
|
21
|
+
# .touches_exact (the state dir itself, as a word)
|
|
20
22
|
# .self_protect .protected and the whole state dir, resolved: what
|
|
21
23
|
# System 1 never answers for (SelfProtect)
|
|
22
24
|
# .review the state dir, the config dir and a hooks dir
|
|
@@ -29,16 +31,23 @@ module Samagotchi
|
|
|
29
31
|
|
|
30
32
|
# chi's config dir, the hooks dir, the approval store's dir, the
|
|
31
33
|
# installed bundles' dir, attached context, the peer mailbox (a message
|
|
32
|
-
# there speaks as a peer)
|
|
33
|
-
# (labels there may train a model: no agent writes them)
|
|
34
|
+
# there speaks as a peer), System 1's saved runs
|
|
35
|
+
# (labels there may train a model: no agent writes them), and
|
|
36
|
+
# schedules.json, a file (#schedules_file: a schedule's prompt and its
|
|
37
|
+
# condition run unattended). The readers match a file root as a dir
|
|
38
|
+
# one: the path itself or under it (PathResolve.under?).
|
|
34
39
|
def protected
|
|
35
40
|
hooks = begin Hooks::Loader.hooks_dir rescue nil end
|
|
36
41
|
bundles = begin MemoryPaths.bundles_dir rescue nil end
|
|
37
42
|
[ConfigFile.config_dir, hooks, File.join(Paths.state_dir, "guardrails"), bundles, File.join(Paths.state_dir, "context"),
|
|
38
|
-
File.join(Paths.state_dir, "mailbox"), File.join(Paths.state_dir, "system_one")]
|
|
43
|
+
File.join(Paths.state_dir, "mailbox"), File.join(Paths.state_dir, "system_one"), schedules_file]
|
|
39
44
|
.compact.map { |dir| dir.to_s.chomp("/") }.reject(&:empty?).uniq
|
|
40
45
|
end
|
|
41
46
|
|
|
47
|
+
# The schedules file, where Schedules#path has it for the default
|
|
48
|
+
# sessions dir: the state root above <state dir>/sessions.
|
|
49
|
+
def schedules_file = File.join(Paths.state_dir, "schedules.json")
|
|
50
|
+
|
|
42
51
|
# .protected (as ParentApprovals.chi_dirs, the name its callers and
|
|
43
52
|
# specs know) and the git hooks dir of +base+'s repo (+context+).
|
|
44
53
|
def touches(context, base)
|
|
@@ -46,6 +55,12 @@ module Samagotchi
|
|
|
46
55
|
ParentApprovals.chi_dirs + [context.hooks_dir(base)].compact
|
|
47
56
|
end
|
|
48
57
|
|
|
58
|
+
# The dirs a shell word touches chi by naming exactly (not what is
|
|
59
|
+
# under them): the state dir, where a copy that names only the dir
|
|
60
|
+
# (`cp /tmp/schedules.json <state>/`, `mv`, `rsync`) lands a file root
|
|
61
|
+
# of .protected. Targets#touches_chi? reads it beside #touches.
|
|
62
|
+
def touches_exact = [Paths.state_dir]
|
|
63
|
+
|
|
49
64
|
# .protected (as ParentApprovals.chi_dirs) and the whole state dir,
|
|
50
65
|
# resolved.
|
|
51
66
|
def self_protect
|
|
@@ -37,7 +37,7 @@ module Samagotchi
|
|
|
37
37
|
# what only looks like one). samagotchi/context and samagotchi/mailbox
|
|
38
38
|
# stop before a word character or a dot, so chi's own
|
|
39
39
|
# lib/samagotchi/context_*.rb isn't one.
|
|
40
|
-
CHI_TEXT = %r{\.config/samagotchi|samagotchi/config\.yml|samagotchi/hooks|samagotchi/guardrails|samagotchi/context(?![\w.])|samagotchi/mailbox(?![\w.])|memories/\.bundles}
|
|
40
|
+
CHI_TEXT = %r{\.config/samagotchi|samagotchi/config\.yml|samagotchi/hooks|samagotchi/guardrails|samagotchi/context(?![\w.])|samagotchi/mailbox(?![\w.])|samagotchi/schedules\.json(?![\w.])|memories/\.bundles}
|
|
41
41
|
# The guardrails bundle's ask before a memory removal: its paths are in
|
|
42
42
|
# the config dir, yet a parent may answer it.
|
|
43
43
|
MEMORY_REMOVE_RULE = "memory-remove"
|
|
@@ -15,8 +15,10 @@ module Samagotchi
|
|
|
15
15
|
# hooks, rules, manifests), attached context (a source's
|
|
16
16
|
# command runs later, outside the gate; chi context writes
|
|
17
17
|
# it), the peer mailbox (a message there speaks as a peer
|
|
18
|
-
# agent; chi peer writes it)
|
|
19
|
-
# label there may train a model)
|
|
18
|
+
# agent; chi peer writes it), System 1's saved runs (a
|
|
19
|
+
# label there may train a model) and schedules.json (a
|
|
20
|
+
# schedule's prompt and condition run unattended; chi schedule
|
|
21
|
+
# writes it); nothing legitimate writes there through a tool
|
|
20
22
|
# that says it writes.
|
|
21
23
|
# ask (once / session): config.yml, home.json (the chi home: the
|
|
22
24
|
# Ruby every chi launch boots), the chi shim (ChiShim: the
|
|
@@ -53,8 +55,9 @@ module Samagotchi
|
|
|
53
55
|
# @param home_path [String, nil] home.json (ChiHome.path)
|
|
54
56
|
# @param shim_path [String, nil] the chi shim (ChiShim.path)
|
|
55
57
|
# @param plugins_dir [String, nil] <state dir>/plugins (the bundles' data, their secrets/ in it)
|
|
58
|
+
# @param schedules_path [String, nil] <state dir>/schedules.json (ChiDirs.schedules_file)
|
|
56
59
|
def initialize(store_dir:, bundles_dir:, config_path:, hooks_dir:, context_dir: nil, runs_dir: nil, home_path: nil, shim_path: nil,
|
|
57
|
-
plugins_dir: nil, mailbox_dir: nil)
|
|
60
|
+
plugins_dir: nil, mailbox_dir: nil, schedules_path: nil)
|
|
58
61
|
@plugins_dir = plugins_dir
|
|
59
62
|
# The same, spelled out: this state dir's own plugins/<x>/secrets.
|
|
60
63
|
@secrets_text = plugins_dir && Regexp.union(SECRETS_TEXT, *([plugins_dir.to_s.chomp("/")] | PathResolve.reals(plugins_dir.to_s.chomp("/"))).map do |dir|
|
|
@@ -65,7 +68,8 @@ module Samagotchi
|
|
|
65
68
|
["installed-bundles", bundles_dir, "installed bundles (hooks, rules, manifests) are changed by chi bundle install"],
|
|
66
69
|
["chi-context", context_dir, "attached context sources run commands; change them with chi context"],
|
|
67
70
|
["chi-mailbox", mailbox_dir, "a message there speaks as a peer agent; chi peer writes the peer mailbox"],
|
|
68
|
-
["system-one-runs", runs_dir, "System 1's saved runs are chi's own record"]
|
|
71
|
+
["system-one-runs", runs_dir, "System 1's saved runs are chi's own record"],
|
|
72
|
+
["chi-schedules", schedules_path, "schedules run commands and prompts unattended; change them with chi schedule"]
|
|
69
73
|
]
|
|
70
74
|
@ask = [
|
|
71
75
|
["chi-config", config_path, "changes chi's config.yml"],
|
|
@@ -39,9 +39,23 @@ module Samagotchi
|
|
|
39
39
|
# @param text [Regexp] the fallback for a word that can't be resolved
|
|
40
40
|
# @param cwd [String, nil] where the command starts
|
|
41
41
|
# @param tmp_roots [Array<String>] where a .git/hooks part doesn't count
|
|
42
|
-
|
|
42
|
+
# @param exact [Array<String>] dirs that count only as themselves, not
|
|
43
|
+
# what is under them (chi's state dir: `cp x <state>/` writes a file
|
|
44
|
+
# root there, schedules.json, by naming only the dir)
|
|
45
|
+
def touches?(command, dirs:, text:, cwd:, home: Dir.home, env: ENV, tmp_roots: [], exact: [])
|
|
43
46
|
roots = dirs.compact.map { |dir| PathResolve.real(dir.to_s.chomp("/")) }.reject(&:empty?).uniq
|
|
44
|
-
|
|
47
|
+
exact = exact.compact.map { |dir| PathResolve.real(dir.to_s.chomp("/")) }.reject(&:empty?).uniq
|
|
48
|
+
any_path?(command, text: text, cwd: cwd, home: home, env: env) do |path|
|
|
49
|
+
names?(path, roots, tmp_roots) || exactly?(path, exact)
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def exactly?(path, exact)
|
|
54
|
+
return false if exact.empty?
|
|
55
|
+
|
|
56
|
+
PathResolve.reals(path.to_s.chomp("/")).any? do |real|
|
|
57
|
+
exact.any? { |dir| PathResolve.under?(real, dir) && PathResolve.under?(dir, real) }
|
|
58
|
+
end
|
|
45
59
|
end
|
|
46
60
|
|
|
47
61
|
# Whether a word of +command+ names a path the block holds for (each
|
|
@@ -510,7 +510,7 @@ module Samagotchi
|
|
|
510
510
|
require_relative "parent_approvals"
|
|
511
511
|
dirs = @chi_dirs ? @chi_dirs.call : ParentApprovals.chi_dirs
|
|
512
512
|
shell_envs.any? do |home, env|
|
|
513
|
-
ShellPaths.touches?(@command, dirs: dirs, text: ParentApprovals::CHI_SHELL_TEXT, cwd: @cwd, home: home,
|
|
513
|
+
ShellPaths.touches?(@command, dirs: dirs, exact: ChiDirs.touches_exact, text: ParentApprovals::CHI_SHELL_TEXT, cwd: @cwd, home: home,
|
|
514
514
|
env: env, tmp_roots: Outside.tmp_roots)
|
|
515
515
|
end
|
|
516
516
|
end
|
|
@@ -20,13 +20,15 @@ module Samagotchi
|
|
|
20
20
|
# parent model would be writing a model's prompt); and the bundle's
|
|
21
21
|
# asks before answering chi's questions around chi answer (a parent
|
|
22
22
|
# allowing one would answer a grandchild's question as the user); and
|
|
23
|
-
# a shell command that names a bundle's secrets (ProtectedPaths)
|
|
23
|
+
# a shell command that names a bundle's secrets (ProtectedPaths); and
|
|
24
|
+
# a schedule's condition set from the shell (chi-schedule-if: a shell
|
|
25
|
+
# command chi's tick runs later, ungated).
|
|
24
26
|
# A parent agent may never allow them (ParentApprovals.protected?,
|
|
25
27
|
# ParentPolicy's user_only); System 1 may, only if the user lists the
|
|
26
28
|
# rule by name in guardrails.system_one.rules, and never for the
|
|
27
|
-
# chi-answer/chi-broadcast ones (SystemOne::SelfProtect::NEVER_AUTO).
|
|
29
|
+
# chi-answer/chi-broadcast/chi-schedule-if ones (SystemOne::SelfProtect::NEVER_AUTO).
|
|
28
30
|
PROTECTED_RULES = %w[chi-config chi-home chi-shim chi-hooks shell-touches-chi chi-context-cmd chi-broadcast prompt-memory-write
|
|
29
|
-
model-overlay-write chi-answer-piped chi-answer-http bundle-secrets-shell].freeze
|
|
31
|
+
model-overlay-write chi-answer-piped chi-answer-http bundle-secrets-shell chi-schedule-if].freeze
|
|
30
32
|
SCOPES = %w[once session repo rule].freeze
|
|
31
33
|
# Who answered an ask when it was a parent agent, not the user.
|
|
32
34
|
PARENT_AGENT = "parent agent"
|
|
@@ -7,6 +7,7 @@ require "securerandom"
|
|
|
7
7
|
require "tmpdir"
|
|
8
8
|
require_relative "atomic_file"
|
|
9
9
|
require_relative "config"
|
|
10
|
+
require_relative "failure_line"
|
|
10
11
|
|
|
11
12
|
module Samagotchi
|
|
12
13
|
# Reads an image's format and size from its first bytes, in pure Ruby.
|
|
@@ -235,7 +236,10 @@ module Samagotchi
|
|
|
235
236
|
# Messages hold small refs to those files; the base64 is built only when
|
|
236
237
|
# a request is sent.
|
|
237
238
|
module ImageStore
|
|
239
|
+
# What the user sent can't be used (UserError: its message as it is).
|
|
238
240
|
class Error < StandardError
|
|
241
|
+
include UserError
|
|
242
|
+
|
|
239
243
|
# A ref to a file this session doesn't hold as an image: one wording
|
|
240
244
|
# for a turn's refs (#check_refs) and a web upload's (#ref_for).
|
|
241
245
|
def self.unknown_image(file) = new("unknown image #{file.to_s[0, 80]}")
|
data/lib/samagotchi/last_turn.rb
CHANGED
|
@@ -54,7 +54,8 @@ module Samagotchi
|
|
|
54
54
|
end
|
|
55
55
|
|
|
56
56
|
# Why a turn stopped, for a parent agent's wait (ReplyWait::Result takes
|
|
57
|
-
# them by these names): a failed turn's
|
|
57
|
+
# them by these names): a failed turn's error kind (a provider's, or
|
|
58
|
+
# chi_error: FailureLine), whether a
|
|
58
59
|
# retry may help and whether its work stayed (kept_steps: a parent must
|
|
59
60
|
# not send the task again); a canceled one's reason and the hook that
|
|
60
61
|
# stopped it.
|
|
@@ -29,6 +29,32 @@ module Samagotchi
|
|
|
29
29
|
obj
|
|
30
30
|
end
|
|
31
31
|
end
|
|
32
|
+
|
|
33
|
+
# +messages+ (a conversation's entries) as a request builds on them:
|
|
34
|
+
# each entry holding a String #call would change (BINARY with high
|
|
35
|
+
# bytes, invalid UTF-8) replaced by its scrubbed copy, before any
|
|
36
|
+
# UTF-8 regex reads it (Steer.wire_text's forged-frame quoting raises
|
|
37
|
+
# on a BINARY string). The same Array when no entry needs it, and the
|
|
38
|
+
# saved entries are never changed: same bytes in, same text out, so a
|
|
39
|
+
# request's prefix (and its prompt cache) is what it was.
|
|
40
|
+
# @param messages [Array<Hash>]
|
|
41
|
+
# @return [Array<Hash>]
|
|
42
|
+
def messages(messages)
|
|
43
|
+
return messages unless messages.any? { |entry| raw?(entry) }
|
|
44
|
+
|
|
45
|
+
messages.map { |entry| raw?(entry) ? call(entry) : entry }
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Whether #call would change a String in +obj+ (at any depth).
|
|
49
|
+
def raw?(obj)
|
|
50
|
+
case obj
|
|
51
|
+
when String
|
|
52
|
+
obj.encoding == Encoding::BINARY ? !obj.ascii_only? : obj.encoding == Encoding::UTF_8 && !obj.valid_encoding?
|
|
53
|
+
when Array then obj.any? { |element| raw?(element) }
|
|
54
|
+
when Hash then obj.any? { |key, value| raw?(key) || raw?(value) }
|
|
55
|
+
else false
|
|
56
|
+
end
|
|
57
|
+
end
|
|
32
58
|
end
|
|
33
59
|
end
|
|
34
60
|
end
|
|
@@ -6,6 +6,7 @@ require_relative "tool_ids"
|
|
|
6
6
|
require_relative "llm_context_edit"
|
|
7
7
|
require_relative "llm_context_stale"
|
|
8
8
|
require_relative "llm_context_strategy"
|
|
9
|
+
require_relative "llm/utf8_scrub"
|
|
9
10
|
|
|
10
11
|
module Samagotchi
|
|
11
12
|
# What the model is sent of the stored conversation: the one step
|
|
@@ -91,9 +92,14 @@ module Samagotchi
|
|
|
91
92
|
|
|
92
93
|
def strategy = none? ? NONE : layers
|
|
93
94
|
|
|
95
|
+
# Every loop's request starts here (ChatLoop#wire_messages, KernelLoop's
|
|
96
|
+
# prompt and warm-up), so raw bytes in the history (a BINARY or invalid
|
|
97
|
+
# UTF-8 String) are read as UTF-8 here, once, before any regex pass
|
|
98
|
+
# (LLM::Utf8Scrub.messages: the stored entries stay as they are).
|
|
94
99
|
# @param conversation [Array<Hash>] the stored entries, in order
|
|
95
100
|
# @return [Array<Hash>] the entries to format
|
|
96
101
|
def messages(conversation)
|
|
102
|
+
conversation = LLM::Utf8Scrub.messages(conversation)
|
|
97
103
|
return conversation if none? && conversation.none? { |entry| LLMContextEdit.drop_on?(entry) }
|
|
98
104
|
|
|
99
105
|
group = Group.new
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
require_relative "log"
|
|
4
4
|
require_relative "model_markup"
|
|
5
|
+
require_relative "failure_line"
|
|
5
6
|
module Samagotchi
|
|
6
7
|
# Encapsulates all model-specific token formats and parsing behavior.
|
|
7
8
|
# Each profile maps to a model family; ModelProfile.resolve picks one
|
|
@@ -17,8 +18,10 @@ module Samagotchi
|
|
|
17
18
|
# (SessionManager.spawn_options, Tools::Builtins.parent_env).
|
|
18
19
|
MODEL_FROM_CLI_ENV = "SAMAGOTCHI_DEFAULT_MODEL_FROM_CLI"
|
|
19
20
|
# No model anywhere (--model, default.model in config.yml, the env): a
|
|
20
|
-
# first run before any config. An ArgumentError, as before
|
|
21
|
+
# first run before any config. An ArgumentError, as before; a failed
|
|
22
|
+
# turn shows its message as it is (UserError).
|
|
21
23
|
class MissingModel < ArgumentError
|
|
24
|
+
include UserError
|
|
22
25
|
end
|
|
23
26
|
|
|
24
27
|
# A host-qualified model whose host isn't configured (a MissingModel,
|
|
@@ -28,14 +28,15 @@ module Samagotchi
|
|
|
28
28
|
# firing's token, its pending turn, extra keys) are chi's bookkeeping.
|
|
29
29
|
SCHEDULE_MEMBERS = %i[id name title mode prompt recurrence_words next_due last_fired last_result enabled state
|
|
30
30
|
off_reason skips max_skips failures max_failures skip_window anchor head created_at
|
|
31
|
-
history].freeze
|
|
31
|
+
history condition].freeze
|
|
32
32
|
|
|
33
33
|
# One schedule as `chi schedule list --format json` says it: +name+ is
|
|
34
34
|
# its title or the start of its prompt in quotes, +state+ "on",
|
|
35
35
|
# "firing" or "off", +off_reason+ why it is off (ScheduleDisplay.off_reason:
|
|
36
36
|
# "owner", "skips", "failures", "done", "missed", "off"; nil when it
|
|
37
|
-
# isn't), +history+ its Runs, oldest first
|
|
38
|
-
#
|
|
37
|
+
# isn't), +history+ its Runs, oldest first, +condition+ the owner's
|
|
38
|
+
# `--if CMD` ({"cmd", "by", "set_at"}; nil for none). Times are ISO
|
|
39
|
+
# 8601 UTC strings, nil when there is none.
|
|
39
40
|
Schedule = Data.define(*SCHEDULE_MEMBERS) do
|
|
40
41
|
# @param json [Hash{String => Object}] ScheduleDisplay.json's; a
|
|
41
42
|
# missing key reads as nil (history as none), an unknown one is
|
|
@@ -53,7 +53,7 @@ module Samagotchi
|
|
|
53
53
|
# @!attribute limit [Integer, nil] the iteration limit an "exhausted"
|
|
54
54
|
# turn ran out at
|
|
55
55
|
# @!attribute error_kind [String, nil] a "failed" turn's provider error
|
|
56
|
-
# kind (credits, server, auth, …), from last_turn
|
|
56
|
+
# kind (credits, server, auth, …) or chi_error, from last_turn
|
|
57
57
|
# @!attribute retryable [Boolean, nil] whether that error may pass on a
|
|
58
58
|
# retry
|
|
59
59
|
# @!attribute cancel_reason [String, nil] a "canceled" turn's reason
|
|
@@ -25,8 +25,9 @@ module Samagotchi
|
|
|
25
25
|
add --session ID (--continues ID) (-m|--message|--prompt TEXT) [--title TEXT]
|
|
26
26
|
one of: --every 30m | --weekday 1 --time 09:00 | --date 2026-11-20T09:00
|
|
27
27
|
[--mode chain|same] [--catch-up once|none] [--keep-links N] [--max-failures N] [--max-skips N]
|
|
28
|
+
[--if CMD]
|
|
28
29
|
edit ID [--title TEXT] [-m|--prompt TEXT] [one recurrence, whole, as add's]
|
|
29
|
-
[--catch-up once|none] [--keep-links N] [--max-failures N] [--max-skips N]
|
|
30
|
+
[--catch-up once|none] [--keep-links N] [--max-failures N] [--max-skips N] [--if CMD | --no-if]
|
|
30
31
|
only the flags given change; the session and mode stay (cancel and add for those);
|
|
31
32
|
a spent --date one-off stays disabled (enable it)
|
|
32
33
|
list [--all] [--format text|json]
|
|
@@ -43,6 +44,9 @@ module Samagotchi
|
|
|
43
44
|
same queues it as a turn in the session itself.
|
|
44
45
|
A busy target is skipped and retried at the next tick; after max_skips skips
|
|
45
46
|
(default 12) or max_failures failures (default 3) the schedule is disabled.
|
|
47
|
+
--if CMD: the tick runs CMD in the session's folder first; exit 0 fires, 1..125
|
|
48
|
+
skips this occurrence quietly ("not needed"), anything else is a failure. From
|
|
49
|
+
your own terminal only (not inside a chi session); run-now doesn't run it.
|
|
46
50
|
TEXT
|
|
47
51
|
|
|
48
52
|
SUBCOMMANDS = %w[add edit list show tick run-now enable disable cancel].freeze
|
|
@@ -70,9 +74,12 @@ module Samagotchi
|
|
|
70
74
|
f.value "--session", "--continues", key: :target
|
|
71
75
|
f.value "--mode"
|
|
72
76
|
FIELD_FLAGS.call(f)
|
|
77
|
+
f.value "--if", key: :condition
|
|
73
78
|
end,
|
|
74
79
|
"edit" => CLI::Flags.new(args: true) do |f|
|
|
75
80
|
FIELD_FLAGS.call(f)
|
|
81
|
+
f.value "--if", key: :condition
|
|
82
|
+
f.switch "--no-if"
|
|
76
83
|
f.refuse "--session", "--continues", "--mode", "edit can't change the session or mode: cancel it and add a new one"
|
|
77
84
|
end,
|
|
78
85
|
"list" => CLI::Flags.new(args: false) do |f|
|
|
@@ -91,12 +98,23 @@ module Samagotchi
|
|
|
91
98
|
}.freeze
|
|
92
99
|
|
|
93
100
|
# @param argv [Array<String>] the arguments after "schedule"
|
|
101
|
+
# A condition runs unattended, outside the guardrails: never set from
|
|
102
|
+
# inside a chi session (an agent), as chi broadcast refuses there too.
|
|
103
|
+
CONDITION_IN_SESSION = "a schedule's condition is set only from your own terminal (chi schedule … --if), " \
|
|
104
|
+
"not from inside a chi session"
|
|
105
|
+
# The older chis that would fire a condition entry unchecked hide it
|
|
106
|
+
# instead (Schedules::ConditionPart): the line add and edit print.
|
|
107
|
+
CONDITION_TICKERS = "every chi that ticks (chi web, cron) must be newer than 0.189.0; " \
|
|
108
|
+
"an older one leaves this schedule alone"
|
|
109
|
+
|
|
94
110
|
# @param schedules [Schedules, nil] the store; default this machine's
|
|
95
|
-
|
|
111
|
+
# @param env [Hash] SAMAGOTCHI_PARENT_SESSION set: run inside a session
|
|
112
|
+
def initialize(argv, stdout: $stdout, stderr: $stderr, schedules: nil, env: ENV)
|
|
96
113
|
@argv = argv.dup
|
|
97
114
|
@stdout = stdout
|
|
98
115
|
@stderr = stderr
|
|
99
116
|
@schedules = schedules || Schedules.new
|
|
117
|
+
@env = env
|
|
100
118
|
end
|
|
101
119
|
|
|
102
120
|
# @return [Integer] exit status: 0 ok, 1 a missing session or schedule,
|
|
@@ -114,6 +132,13 @@ module Samagotchi
|
|
|
114
132
|
|
|
115
133
|
@opts = parsed.options
|
|
116
134
|
@args = parsed.args
|
|
135
|
+
if @opts.key?(:condition) || @opts[:no_if]
|
|
136
|
+
unless @env["SAMAGOTCHI_PARENT_SESSION"].to_s.empty?
|
|
137
|
+
error_line("#{command_name}: #{CONDITION_IN_SESSION}")
|
|
138
|
+
return CLI::Exit::USAGE
|
|
139
|
+
end
|
|
140
|
+
return usage_error("--if and --no-if together: give one") if @opts.key?(:condition) && @opts[:no_if]
|
|
141
|
+
end
|
|
117
142
|
|
|
118
143
|
case sub
|
|
119
144
|
when "add" then add
|
|
@@ -142,7 +167,8 @@ module Samagotchi
|
|
|
142
167
|
entry = @schedules.add(target: @opts[:target], prompt: @opts[:prompt], recurrence: recurrence,
|
|
143
168
|
title: @opts[:title], mode: @opts[:mode] || Schedules::CHAIN,
|
|
144
169
|
catch_up: @opts[:catch_up], keep_links: @opts[:keep_links],
|
|
145
|
-
max_failures: @opts[:max_failures], max_skips: @opts[:max_skips]
|
|
170
|
+
max_failures: @opts[:max_failures], max_skips: @opts[:max_skips],
|
|
171
|
+
condition: @opts[:condition])
|
|
146
172
|
rescue Schedules::Usage => e
|
|
147
173
|
return usage_error(e.message)
|
|
148
174
|
rescue Session::AmbiguousId => e
|
|
@@ -151,7 +177,12 @@ module Samagotchi
|
|
|
151
177
|
return failed("no session #{@opts[:target]}")
|
|
152
178
|
end
|
|
153
179
|
|
|
154
|
-
@stdout.puts("#{entry.id} added: #{entry.target_words} · #{entry.recurrence_words}
|
|
180
|
+
@stdout.puts("#{entry.id} added: #{entry.target_words} · #{entry.recurrence_words}#{condition_words(entry)} · " \
|
|
181
|
+
"next #{clock(entry.next_due)}")
|
|
182
|
+
if entry.condition
|
|
183
|
+
@stdout.puts(CONDITION_TICKERS)
|
|
184
|
+
print_gate_warning(entry)
|
|
185
|
+
end
|
|
155
186
|
print_tick_warning
|
|
156
187
|
CLI::Exit::OK
|
|
157
188
|
end
|
|
@@ -165,12 +196,17 @@ module Samagotchi
|
|
|
165
196
|
recurrence = if %i[every weekday time date].any? { |key| @opts.key?(key) }
|
|
166
197
|
Schedules.recurrence(every: @opts[:every], weekday: @opts[:weekday], time: @opts[:time], date: @opts[:date])
|
|
167
198
|
end
|
|
199
|
+
condition = @opts[:no_if] ? :none : @opts[:condition]
|
|
168
200
|
entry = @schedules.edit(id, title: @opts[:title], prompt: @opts[:prompt], recurrence: recurrence,
|
|
169
201
|
catch_up: @opts[:catch_up], keep_links: @opts[:keep_links],
|
|
170
|
-
max_failures: @opts[:max_failures], max_skips: @opts[:max_skips])
|
|
202
|
+
max_failures: @opts[:max_failures], max_skips: @opts[:max_skips], condition: condition)
|
|
171
203
|
return failed("no schedule #{id}") if entry.nil?
|
|
172
204
|
|
|
173
205
|
@stdout.puts(entry_line(entry))
|
|
206
|
+
if @opts.key?(:condition)
|
|
207
|
+
@stdout.puts(CONDITION_TICKERS)
|
|
208
|
+
print_gate_warning(entry)
|
|
209
|
+
end
|
|
174
210
|
CLI::Exit::OK
|
|
175
211
|
rescue Schedules::EditPart::InFlight => e
|
|
176
212
|
failed(e.message)
|
|
@@ -183,18 +219,22 @@ module Samagotchi
|
|
|
183
219
|
return refused if refused
|
|
184
220
|
|
|
185
221
|
entries = @schedules.entries(include_disabled: @opts[:include_disabled] ? true : false)
|
|
222
|
+
unreadable = unreadable_line
|
|
186
223
|
if @opts[:format] == "json"
|
|
187
224
|
@stdout.puts(JSON.pretty_generate(entries.map { |entry| entry_line_json(entry) }))
|
|
225
|
+
@stderr.puts(unreadable) if unreadable
|
|
188
226
|
print_tick_warning(@stderr)
|
|
189
227
|
return CLI::Exit::OK
|
|
190
228
|
end
|
|
191
229
|
if entries.empty?
|
|
192
230
|
@stdout.puts("no schedules")
|
|
231
|
+
@stdout.puts(unreadable) if unreadable
|
|
193
232
|
print_tick_warning
|
|
194
233
|
return CLI::Exit::OK
|
|
195
234
|
end
|
|
196
235
|
name_width = ScheduleDisplay.name_width(entries)
|
|
197
236
|
entries.each { |entry| @stdout.puts(entry_line(entry, name_width: name_width)) }
|
|
237
|
+
@stdout.puts(unreadable) if unreadable
|
|
198
238
|
print_tick_warning
|
|
199
239
|
CLI::Exit::OK
|
|
200
240
|
end
|
|
@@ -212,6 +252,7 @@ module Samagotchi
|
|
|
212
252
|
@stdout.puts(" last fired: #{clock(entry.last_fired)} last result: #{entry.last_result || "-"}")
|
|
213
253
|
@stdout.puts(" skips: #{entry.skips} of #{entry.max_skips} failures: #{entry.failures} of #{entry.max_failures}")
|
|
214
254
|
@stdout.puts(" keep_links: #{entry.keep_links} enabled: #{entry.enabled}")
|
|
255
|
+
@stdout.puts(" if: #{condition_show(entry)}") unless entry.condition.nil?
|
|
215
256
|
@stdout.puts(" prompt: #{entry.prompt}")
|
|
216
257
|
print_history(entry)
|
|
217
258
|
CLI::Exit::OK
|
|
@@ -304,11 +345,40 @@ module Samagotchi
|
|
|
304
345
|
note = ""
|
|
305
346
|
note += " skips #{entry.skips} of #{entry.max_skips} (#{ScheduleDisplay.skip_window(entry)})" if entry.skips.positive?
|
|
306
347
|
note += off_note(entry) unless entry.enabled
|
|
348
|
+
note += " if: #{ScheduleDisplay.condition_words(entry, chars: ScheduleDisplay::PROMPT_CHARS)}" unless entry.condition.nil?
|
|
307
349
|
note += " last: #{entry.last_result}" if entry.last_result
|
|
308
350
|
"#{entry.id} #{ScheduleDisplay.name(entry, width: name_width)} #{entry.mode} #{entry.recurrence_words} " \
|
|
309
351
|
"#{clock(entry.next_due)} #{entry.head[0, 8]}#{note}"
|
|
310
352
|
end
|
|
311
353
|
|
|
354
|
+
# Schedules::ConditionPart.gate_warning for the folder CMD runs in (the
|
|
355
|
+
# target session's), when CMD is a script the model can edit.
|
|
356
|
+
def print_gate_warning(entry)
|
|
357
|
+
cmd = entry.condition.is_a?(Hash) ? entry.condition[:cmd] : nil
|
|
358
|
+
return unless cmd.is_a?(String)
|
|
359
|
+
|
|
360
|
+
folder = begin
|
|
361
|
+
Session.load(entry.head, state_dir: @schedules.state_dir).working_directory
|
|
362
|
+
rescue Session::NotFound
|
|
363
|
+
nil
|
|
364
|
+
end
|
|
365
|
+
warning = Schedules::ConditionPart.gate_warning(cmd, folder: folder)
|
|
366
|
+
@stdout.puts(warning) if warning
|
|
367
|
+
end
|
|
368
|
+
|
|
369
|
+
# " · if CMD" for add's line, "" without a condition.
|
|
370
|
+
def condition_words(entry) = entry.condition.nil? ? "" : " · if #{ScheduleDisplay.condition_words(entry)}"
|
|
371
|
+
|
|
372
|
+
# show's: the command, who set it and when, and what holds for it.
|
|
373
|
+
def condition_show(entry)
|
|
374
|
+
condition = entry.condition
|
|
375
|
+
return ScheduleDisplay.condition_words(entry) unless condition.is_a?(Hash) && condition[:cmd].is_a?(String)
|
|
376
|
+
|
|
377
|
+
by = condition[:by] == Schedules::ConditionPart::CONDITION_BY ? "the CLI" : condition[:by].inspect
|
|
378
|
+
"#{condition[:cmd]} (set from #{by} #{clock(condition[:set_at])}; timeout #{@schedules.condition_timeout_seconds} s; " \
|
|
379
|
+
"run-now skips it)"
|
|
380
|
+
end
|
|
381
|
+
|
|
312
382
|
def off_note(entry)
|
|
313
383
|
case ScheduleDisplay.off_reason(entry)
|
|
314
384
|
when "skips"
|
|
@@ -325,6 +395,30 @@ module Samagotchi
|
|
|
325
395
|
|
|
326
396
|
def entry_line_json(entry) = ScheduleDisplay.json(entry)
|
|
327
397
|
|
|
398
|
+
# The entries of schedules.json that don't read, which list leaves out:
|
|
399
|
+
# one line naming them and the way out (Schedules#cancel takes one by its
|
|
400
|
+
# id, #cancel_unreadable), nil when there are none. A file that isn't
|
|
401
|
+
# JSON lists as no schedules, as before.
|
|
402
|
+
UNREADABLE_IDS_SHOWN = 5
|
|
403
|
+
|
|
404
|
+
def unreadable_line
|
|
405
|
+
ids = @schedules.listing.unreadable_ids
|
|
406
|
+
named = ids.compact
|
|
407
|
+
nameless = ids.size - named.size
|
|
408
|
+
parts = []
|
|
409
|
+
unless named.empty?
|
|
410
|
+
shown = named.first(UNREADABLE_IDS_SHOWN).join(", ")
|
|
411
|
+
shown += ", …" if named.size > UNREADABLE_IDS_SHOWN
|
|
412
|
+
parts << "#{plural(named.size, "schedule")} can't be read (#{shown}): chi schedule cancel ID removes one"
|
|
413
|
+
end
|
|
414
|
+
parts << "#{plural(nameless, "schedule")} with no id can't be read: fix or remove it in schedules.json" if nameless.positive?
|
|
415
|
+
parts.empty? ? nil : parts.join("; ")
|
|
416
|
+
rescue Schedules::Corrupt
|
|
417
|
+
nil
|
|
418
|
+
end
|
|
419
|
+
|
|
420
|
+
def plural(count, word) = "#{count} #{word}#{"s" unless count == 1}"
|
|
421
|
+
|
|
328
422
|
def print_tick_warning(stream = @stdout)
|
|
329
423
|
warning = @schedules.tick_warning
|
|
330
424
|
stream.puts(warning) if warning
|