samagotchi 0.180.0 → 0.182.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 +71 -1
- data/bin/chi +11 -0
- data/docs/architecture.md +2 -2
- data/docs/bundles.md +7 -2
- data/docs/cli.md +46 -13
- data/docs/configuration.md +25 -4
- data/docs/internals/anthropic.md +4 -3
- data/docs/internals/background-tasks.md +2 -0
- data/docs/internals/block-renderers.md +123 -6
- data/docs/internals/bridge.md +10 -0
- data/docs/internals/engine.md +11 -0
- data/docs/internals/inline-widgets.md +3 -1
- data/docs/internals/objectives.md +9 -4
- data/docs/internals/prompt-caching.md +9 -1
- data/docs/internals/remote-sessions.md +14 -2
- data/docs/internals/web-frontend.md +100 -10
- data/docs/internals/working-set.md +24 -5
- data/docs/memory.md +3 -0
- data/docs/plugins.md +11 -4
- data/docs/sessions.md +8 -5
- data/docs/testing.md +1 -1
- data/lib/samagotchi/answer_display.rb +3 -2
- data/lib/samagotchi/block_fix/stamp.rb +49 -0
- data/lib/samagotchi/block_fix.rb +220 -0
- data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
- data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
- data/lib/samagotchi/bridge.rb +11 -2
- data/lib/samagotchi/bridge_client.rb +9 -0
- data/lib/samagotchi/bundle_command.rb +4 -1
- data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
- data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
- data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
- data/lib/samagotchi/bundles/system/manifest.yml +2 -2
- data/lib/samagotchi/client.rb +8 -1
- data/lib/samagotchi/config.rb +9 -1
- data/lib/samagotchi/continue_intent.rb +8 -0
- data/lib/samagotchi/core_notice.rb +44 -0
- data/lib/samagotchi/engine/block_fix.rb +332 -0
- data/lib/samagotchi/engine/side_requests.rb +7 -5
- data/lib/samagotchi/engine.rb +4 -0
- data/lib/samagotchi/events.rb +1 -0
- data/lib/samagotchi/host_address.rb +7 -0
- data/lib/samagotchi/host_config.rb +8 -5
- data/lib/samagotchi/host_registry.rb +26 -8
- data/lib/samagotchi/idle_client.rb +10 -6
- data/lib/samagotchi/inline_widgets.rb +12 -0
- data/lib/samagotchi/kernel_loop.rb +10 -7
- data/lib/samagotchi/llm/adapter_common.rb +3 -2
- data/lib/samagotchi/llm/adapters.rb +2 -1
- data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
- data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
- data/lib/samagotchi/llm/chat_loop.rb +8 -5
- data/lib/samagotchi/llm/errors.rb +41 -3
- data/lib/samagotchi/llm/http.rb +85 -22
- data/lib/samagotchi/llm/openai_chat.rb +20 -3
- data/lib/samagotchi/markdown_parser.rb +28 -0
- data/lib/samagotchi/memory_bundle/status.rb +2 -1
- data/lib/samagotchi/objectives.rb +7 -2
- data/lib/samagotchi/owner_lock.rb +2 -0
- data/lib/samagotchi/plugin/api.rb +4 -1
- data/lib/samagotchi/plugin/context.rb +9 -0
- data/lib/samagotchi/plugin/peer.rb +32 -15
- data/lib/samagotchi/plugin/tool_spec.rb +13 -2
- data/lib/samagotchi/row_refs.rb +14 -3
- data/lib/samagotchi/session_access/contract.rb +3 -0
- data/lib/samagotchi/session_access/delete_plan.rb +77 -0
- data/lib/samagotchi/session_access/local.rb +13 -0
- data/lib/samagotchi/session_access/remote.rb +19 -1
- data/lib/samagotchi/session_access.rb +1 -0
- data/lib/samagotchi/session_chain/delete.rb +45 -87
- data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
- data/lib/samagotchi/session_delete_command.rb +129 -3
- data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
- data/lib/samagotchi/session_manager/listing.rb +4 -4
- data/lib/samagotchi/session_manager/removal.rb +40 -14
- data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
- data/lib/samagotchi/session_manager.rb +1 -0
- data/lib/samagotchi/tool_ids.rb +19 -0
- data/lib/samagotchi/tool_runner.rb +8 -4
- data/lib/samagotchi/tools/registry.rb +3 -2
- data/lib/samagotchi/tools/task_runtime.rb +34 -0
- data/lib/samagotchi/turn_stages/objectives.rb +10 -5
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +13 -1
- data/lib/samagotchi/web/block_fix_routes.rb +39 -0
- data/lib/samagotchi/web/markdown_renderer.rb +24 -9
- data/lib/samagotchi/web/message_display.rb +6 -1
- data/lib/samagotchi/web/participant_view.rb +1 -1
- data/lib/samagotchi/web/public/app.js +15 -19
- data/lib/samagotchi/web/public/block_fix.js +270 -0
- data/lib/samagotchi/web/public/block_fix_note.js +104 -0
- data/lib/samagotchi/web/public/block_frame.js +6 -3
- data/lib/samagotchi/web/public/block_host.js +21 -21
- data/lib/samagotchi/web/public/block_renderers.css +17 -5
- data/lib/samagotchi/web/public/block_watch.js +16 -2
- data/lib/samagotchi/web/public/context_chips.js +3 -4
- data/lib/samagotchi/web/public/images.js +1 -1
- data/lib/samagotchi/web/public/index.html +24 -5
- data/lib/samagotchi/web/public/inline_widgets.js +1 -1
- data/lib/samagotchi/web/public/objectives_strip.js +16 -6
- data/lib/samagotchi/web/public/pan_zoom.js +121 -0
- data/lib/samagotchi/web/public/peer_chip.js +3 -3
- data/lib/samagotchi/web/public/peer_data.js +27 -15
- data/lib/samagotchi/web/public/picture_viewer.js +304 -0
- data/lib/samagotchi/web/public/popover_modal.js +3 -2
- data/lib/samagotchi/web/public/session_view.js +4 -0
- data/lib/samagotchi/web/public/stream_handlers.js +5 -1
- data/lib/samagotchi/web/public/turn_block.js +5 -2
- data/lib/samagotchi/web/public/working_set.js +9 -3
- data/lib/samagotchi/web/public/working_set_view.js +28 -11
- data/lib/samagotchi/web/public/ws_cards.js +36 -10
- data/lib/samagotchi/web/public/ws_markdown.js +129 -0
- data/lib/samagotchi/web/public/ws_order.js +48 -0
- data/lib/samagotchi/web/public/ws_peek.js +22 -5
- data/lib/samagotchi/web/public/ws_preview.css +41 -1
- data/lib/samagotchi/web/public/ws_reader.js +35 -6
- data/lib/samagotchi/web/public/ws_sections.js +24 -15
- data/lib/samagotchi/web/server.rb +6 -4
- data/lib/samagotchi/web/session_control.rb +53 -21
- data/lib/samagotchi/worker/block_fixes.rb +22 -0
- data/lib/samagotchi/worker.rb +10 -3
- metadata +17 -1
data/lib/samagotchi/bridge.rb
CHANGED
|
@@ -15,6 +15,7 @@ require_relative "delivery"
|
|
|
15
15
|
require_relative "session_inbox"
|
|
16
16
|
require_relative "turn_anchors"
|
|
17
17
|
|
|
18
|
+
require_relative "bridge/block_fix_route"
|
|
18
19
|
require_relative "bridge/bounded_queue"
|
|
19
20
|
require_relative "bridge/card_store"
|
|
20
21
|
require_relative "bridge/event_id"
|
|
@@ -65,6 +66,8 @@ module Samagotchi
|
|
|
65
66
|
# * Optional at runtime: this module is never loaded unless explicitly
|
|
66
67
|
# engaged as a transport.
|
|
67
68
|
class Bridge
|
|
69
|
+
include BlockFixRoute
|
|
70
|
+
|
|
68
71
|
ENGINE_CALLS = {
|
|
69
72
|
active_cancel_controller: "turn-state monitor",
|
|
70
73
|
annotate_question: "question-desk control",
|
|
@@ -76,6 +79,7 @@ module Samagotchi
|
|
|
76
79
|
cut_for_steer: "steer-cut coordination",
|
|
77
80
|
drop_enqueued_id: "turn-state monitor",
|
|
78
81
|
enqueued_id?: "turn-state monitor",
|
|
82
|
+
fix_block: "block-fix mutex; replace-only session messages",
|
|
79
83
|
event_count: "observer-registry monitor",
|
|
80
84
|
forget_enqueued_id: "turn-state monitor",
|
|
81
85
|
generation_snapshot: "generation-phase snapshot",
|
|
@@ -286,6 +290,7 @@ module Samagotchi
|
|
|
286
290
|
@port = @server.local_address.ip_port
|
|
287
291
|
@capture_handle = @engine.subscribe(observer: capture_observer)
|
|
288
292
|
@accumulator_handle = @engine.subscribe(observer: @accumulator)
|
|
293
|
+
@drawings_handle = @engine.subscribe(observer: @drawings)
|
|
289
294
|
# A plugin's ctx.messages mid-turn holds the turn so far (plan O1).
|
|
290
295
|
@engine.running_turn_messages = -> { @accumulator.current_messages }
|
|
291
296
|
@cards_handle = @engine.subscribe(observer: @cards)
|
|
@@ -342,6 +347,7 @@ module Samagotchi
|
|
|
342
347
|
wake_acceptor
|
|
343
348
|
@capture_handle&.unsubscribe
|
|
344
349
|
@accumulator_handle&.unsubscribe
|
|
350
|
+
@drawings_handle&.unsubscribe
|
|
345
351
|
@engine.running_turn_messages = nil
|
|
346
352
|
@cards_handle&.unsubscribe
|
|
347
353
|
@pending_card_handle&.unsubscribe
|
|
@@ -813,7 +819,7 @@ module Samagotchi
|
|
|
813
819
|
SessionInbox::UNQUEUE_FEATURE, Delivery::REVIEW_FEATURE, Delivery::PAIR_FEATURE, TurnDrawings::FEATURE,
|
|
814
820
|
WorkerLink::ACTIVITY_FEATURE, ObjectivesTrack::FEATURE, Delivery::OWN_TURN_STEER_FEATURE,
|
|
815
821
|
Delivery::CANCEL_TURN_ID_FEATURE, ReviseAnchor::PARTICIPANT_FEATURE, Delivery::PARTICIPANT_ID_FEATURE,
|
|
816
|
-
WorkingSet::ITEM_FEATURE].freeze
|
|
822
|
+
WorkingSet::ITEM_FEATURE, BlockFix::FEATURE].freeze
|
|
817
823
|
|
|
818
824
|
# The routes, by method and what follows /session/:id/: a handler takes
|
|
819
825
|
# the session id and the request body and returns [headers, status, body].
|
|
@@ -839,7 +845,8 @@ module Samagotchi
|
|
|
839
845
|
%w[GET stats] => :handle_stats,
|
|
840
846
|
%w[GET snapshot] => :handle_snapshot,
|
|
841
847
|
%w[GET tail] => :handle_tail,
|
|
842
|
-
%w[GET working_set/item] => :handle_working_set_item
|
|
848
|
+
%w[GET working_set/item] => :handle_working_set_item,
|
|
849
|
+
%w[POST blocks/fix] => :handle_block_fix
|
|
843
850
|
}.freeze
|
|
844
851
|
ROUTE_PATH = %r{\A/session/([^/]+)/(.+)\z}u
|
|
845
852
|
# The handlers that take the request's query string as a third
|
|
@@ -1853,6 +1860,8 @@ module Samagotchi
|
|
|
1853
1860
|
403 => "Forbidden",
|
|
1854
1861
|
404 => "Not Found",
|
|
1855
1862
|
409 => "Conflict",
|
|
1863
|
+
413 => "Content Too Large",
|
|
1864
|
+
429 => "Too Many Requests",
|
|
1856
1865
|
500 => "Internal Server Error",
|
|
1857
1866
|
501 => "Not Implemented"
|
|
1858
1867
|
}.freeze
|
|
@@ -172,6 +172,15 @@ module Samagotchi
|
|
|
172
172
|
post("guardrails/wrong", { id: judgment_id }, read_body: true)
|
|
173
173
|
end
|
|
174
174
|
|
|
175
|
+
# POST /session/:id/blocks/fix: ask again, once, for a block the page
|
|
176
|
+
# couldn't draw in +turn_id+'s answer (Bridge::BlockFixRoute). 200 asked
|
|
177
|
+
# before, 202 asking, 400/409/413/429 refused; 404: a worker older than
|
|
178
|
+
# the route.
|
|
179
|
+
# @return [Response]
|
|
180
|
+
def fix_block(turn_id:, lang:, source:, reason:)
|
|
181
|
+
post("blocks/fix", { turn_id: turn_id, lang: lang, source: source, reason: reason }, read_body: true)
|
|
182
|
+
end
|
|
183
|
+
|
|
175
184
|
# POST /session/:id/turn/dequeue: take back a queued message (one that
|
|
176
185
|
# waits for the running turn's end) before it runs. 200 {status:
|
|
177
186
|
# "removed", enqueued_id, prompt}; 409 already_started (a turn took
|
|
@@ -626,7 +626,10 @@ module Samagotchi
|
|
|
626
626
|
return if states.empty?
|
|
627
627
|
|
|
628
628
|
@stdout.puts " #{heading} (#{states.size}):"
|
|
629
|
-
states.each
|
|
629
|
+
states.each do |file, state|
|
|
630
|
+
note = state == "unrecorded" ? PLUGIN_NOTES.fetch(state) : (modified if state == "modified")
|
|
631
|
+
@stdout.puts " #{file} [#{state}]#{note}"
|
|
632
|
+
end
|
|
630
633
|
end
|
|
631
634
|
|
|
632
635
|
# "Manifest: [kept]", or "[from the install record]", and what its case
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: known-names
|
|
3
|
-
version: 0.2.
|
|
3
|
+
version: 0.2.1
|
|
4
4
|
requires_chi: ">= 0.150.0"
|
|
5
5
|
scope: system
|
|
6
6
|
description: Catches a near-miss of a protected name (home folder, login, git name, repo name, names from config) in a tool call and rejects it with the right spelling; mode ask / correct optional
|
|
@@ -9,6 +9,6 @@ files:
|
|
|
9
9
|
known_names.md: sha256:d5348b95b6c655017b541910b36e384220da280818160201f6ec9a50e1e4287c
|
|
10
10
|
plugin:
|
|
11
11
|
file: plugin.rb
|
|
12
|
-
sha256: sha256:
|
|
12
|
+
sha256: sha256:f519ec42023a6857f87fba9ff8a8db5d261dccfd88e3a9b58310ae3293b3cbdc
|
|
13
13
|
# config.yml bundles: known-names: (another key warns; an older chi ignores this)
|
|
14
14
|
settings: [names, ignore, mode, derive, min_length, max_distance]
|
|
@@ -24,9 +24,10 @@ class KnownNames
|
|
|
24
24
|
DERIVATIONS = %w[home user git repo].freeze
|
|
25
25
|
DEFAULT_MIN_LENGTH = 6
|
|
26
26
|
# Splits a command or path into tokens; each token's [-_.] parts are
|
|
27
|
-
# candidates too. "
|
|
28
|
-
# name
|
|
29
|
-
|
|
27
|
+
# candidates too. Backticks, "$" and "!" split: shell/markdown wrappers
|
|
28
|
+
# and prefixes, not part of a name. "#" and "~" split: in "~name" (that
|
|
29
|
+
# user's home) the name after it is what is checked.
|
|
30
|
+
TOKEN_SPLIT = %r{[/\s"'=:,;|&()<>@~#!$`]+}
|
|
30
31
|
PART_SPLIT = /[-_.]+/
|
|
31
32
|
# Separators at a token's start or end, dropped before it is compared.
|
|
32
33
|
EDGE_SEPARATORS = /\A[-_.]+|[-_.]+\z/
|
|
@@ -18,7 +18,7 @@ Single registry `Samagotchi::Config` (`Config::ENTRIES` in `lib/samagotchi/confi
|
|
|
18
18
|
|
|
19
19
|
Sections forbid `_`/`-` (`SECTION_RE` `/\A[a-z0-9]+\z/`), since an env or CLI name is derived from them; a config-only section (`system_one`: `expose: [:config]`, no derived name) may carry `_`. Leaves keep `snake_case` in YAML (`base_url`) and become kebab in CLI (`base-url`) via registry derivation — no generic string split, registry lookup avoids flat vs nested collision.
|
|
20
20
|
|
|
21
|
-
**Universal entries** (`expose: [:env,:config,:cli]`): `default.model`, `server.host/port/open_timeout/read_timeout`, `server.first_token_timeout` (env and config only), `recap.model/base_url/host_ref/inactivity/timeout/min_user_turns/sentences`, `session.retention_days/max_count/keep_status/sweep_interval_hours/idle_exit_minutes`, `session.keep_empty/max_children` (env and config only), `log.file/disable`, `status.line`, `context.status/window_tokens/chars_per_token/status_thresholds`, `memory.index_warn_tokens/entry_warn_tokens/read_max_chars`, `default.max_tokens`, `max_tool_output_chars`, `retry.max/base_delay/max_delay`, `read.*`, `execute.*`, `web.port/host`, `no_interrupt`, `no_default_input` etc. (`Config::ENTRIES`; `expose` says which of env/config/cli each takes). Precedence is `CLI > ENV > file > default`.
|
|
21
|
+
**Universal entries** (`expose: [:env,:config,:cli]`): `default.model`, `server.host/port/open_timeout/read_timeout`, `server.first_token_timeout`, `server.stream_idle_timeout` (env and config only), `recap.model/base_url/host_ref/inactivity/timeout/min_user_turns/sentences`, `session.retention_days/max_count/keep_status/sweep_interval_hours/idle_exit_minutes`, `session.keep_empty/max_children` (env and config only), `log.file/disable`, `status.line`, `context.status/window_tokens/chars_per_token/status_thresholds`, `memory.index_warn_tokens/entry_warn_tokens/read_max_chars`, `default.max_tokens`, `max_tool_output_chars`, `retry.max/base_delay/max_delay`, `read.*`, `execute.*`, `web.port/host`, `no_interrupt`, `no_default_input` etc. (`Config::ENTRIES`; `expose` says which of env/config/cli each takes). Precedence is `CLI > ENV > file > default`.
|
|
22
22
|
|
|
23
23
|
Example `config.yml` (new nested form, preferred):
|
|
24
24
|
|
|
@@ -30,6 +30,7 @@ server:
|
|
|
30
30
|
host: localhost
|
|
31
31
|
port: 8080
|
|
32
32
|
first_token_timeout: 120 # seconds a request may wait for its first token; 0 = off; unset: 120 for remote hosts, none for local
|
|
33
|
+
stream_idle_timeout: 120 # seconds a stream that showed something may go without more; 0 = off; unset: 120 for remote hosts, none for local
|
|
33
34
|
recap:
|
|
34
35
|
host_ref: small-box # a name under hosts:, or base_url: http://...
|
|
35
36
|
model: your-small-model-id
|
|
@@ -55,7 +56,7 @@ Only the nested form is read. An env name used as a top-level key (`SAMAGOTCHI_D
|
|
|
55
56
|
**Excluded maps** (YAML-only, not part of the flat registry; skipped by scalar loader):
|
|
56
57
|
|
|
57
58
|
- `model_aliases:` map of alias → model id (`ModelRef.parse`, through `HostRegistry#resolve`). Keys lowercased on write (`ConfigFile.write_model_alias!`). Values may be bare `model` or qualified `host:model` (hybrid; only `:` names a host, `org/model` is an id). Aliases apply once: never point an alias at another alias.
|
|
58
|
-
- `hosts:` map of `name → {host, port | url, api, api_key_env, auth, dialect, profile, first_token_timeout, vision, sampling, thinking, enabled, models}` (`HostConfig.all`, `host_registry.rb` `HostEntry`). Names lowercased; `url:` (http/https, optional path) replaces host/port, never both; `api_key_env:` names the env var holding the API key (never write a key into config.yml); `auth:` (`bearer|x-api-key`) is the header the key goes in (default `x-api-key` on `api: anthropic`, Bearer elsewhere); `dialect:` (`fireworks`, or `standard` for the default; `api: anthropic` only) adjusts the Messages wire for that provider (Bearer by default, no thinking `display`, no `cache_control`, `x-session-affinity`; `LLM::Dialect`, docs/configuration.md "Anthropic Messages hosts"); `first_token_timeout` (seconds, `0` = off; a negative or non-number warns and is ignored) overrides `server.first_token_timeout` for that host
|
|
59
|
+
- `hosts:` map of `name → {host, port | url, api, api_key_env, auth, dialect, profile, first_token_timeout, stream_idle_timeout, vision, sampling, thinking, enabled, models}` (`HostConfig.all`, `host_registry.rb` `HostEntry`). Names lowercased; `url:` (http/https, optional path) replaces host/port, never both; `api_key_env:` names the env var holding the API key (never write a key into config.yml); `auth:` (`bearer|x-api-key`) is the header the key goes in (default `x-api-key` on `api: anthropic`, Bearer elsewhere); `dialect:` (`fireworks`, or `standard` for the default; `api: anthropic` only) adjusts the Messages wire for that provider (Bearer by default, no thinking `display`, no `cache_control`, `x-session-affinity`; `LLM::Dialect`, docs/configuration.md "Anthropic Messages hosts"); `first_token_timeout` (seconds, `0` = off; a negative or non-number warns and is ignored) overrides `server.first_token_timeout` for that host, as `stream_idle_timeout` does `server.stream_idle_timeout`; `models:` (a map of model ids, or a plain list) declares ids the host serves whatever its `/v1/models` lists: no "doesn't list" warning, and a bare id routes there as if listed (`HostModel`); an entry may hold `price: {input, output, cache_read?, cache_write?}` in USD per 1M tokens (`ModelPrice`; an unset cache rate is the input rate), which estimates a cost the provider doesn't report or reports as 0 (`cost_estimate`, shown as `~$`), and `served: [ids] | any`, the models a gateway may answer that id with (no served-model warning for them); model settings stay in the root `models:`; a worker reads `hosts:` from the file as it starts (no environment variable sets hosts).
|
|
59
60
|
- `models:` map of model id or alias → `{profile, vision, sampling, thinking, reasoning_history}` (`ModelSettings.all`). `thinking:` (here, on a host, or `thinking.level` for every model) is `off|low|medium|high|default` (`Thinking`; unquoted `off` works, `on` is not a level; `default` = send nothing). Precedence: the session's own level (`/thinking LEVEL`, saved in the session; `chi --thinking` on a session run, `chi send --new --thinking`) > `chi web --thinking`/`SAMAGOTCHI_THINKING_LEVEL` > `models:` > `hosts.<name>.thinking` > `thinking.level` in config.yml > `default`. A `sampling:` key wins over the fields a level sends (`null` drops one); `docs/configuration.md` "Thinking". `reasoning_history:` (here or on a host) is `drop|turn|all`, which of its reasoning a chat host's model gets back. Precedence: the session's own level (`/reasoning-history LEVEL`, saved in the session) > `SAMAGOTCHI_REASONING_HISTORY` > `models:` > `hosts.<name>.reasoning_history` > `turn`; `docs/configuration.md` "Reasoning history". `/thinking` and `/reasoning-history` ask before a change that restarts the prompt cache; `--yes` applies it (`chi send` commands apply directly). `sampling:` (here or on a host) is a map of request fields passed to the provider as written (`temperature`, `top_p`, `presence_penalty`, `repeat_penalty`, …; a model's fields win over its host's per field; `null` = don't send; chi's own fields like `max_tokens`/`stream` are refused with a warning; `docs/configuration.md` "Sampling"). Keys match case-insensitively. `profile` (here or on a host) is `qwen36|gemma4`: the raw prompt format for native hosts. Precedence: `--profile`/`SAMAGOTCHI_MODEL_PROFILE` > `models:` > `hosts.<name>.profile` > the llama.cpp server's chat template > the name (`qwen`/`gemma`) > `qwen36` (`ModelProfile.resolve`). Set one when a model's name hides its family (e.g. a Qwen fine-tune under another name whose server publishes no template).
|
|
60
61
|
- `hooks:` map of `hooks_dir` + per-event lists `{path, on_error}` (`Hooks::Loader.load`). `hooks_dir` may start with `~`.
|
|
61
62
|
- `guardrails:` tool-call rules (`docs/guardrails.md`; read in `Engine#guardrail_rules`, parsed by `Guardrails::Rules.parse`): `enabled` (bool, default true; `false` drops rules and hooks' asks, a deny still applies; config.yml only, like every `guardrails` setting: no env variable), `parent_answers` (`soft`, the default: a parent agent's `chi answer` may deny, answer, Continue and give "Allow once"; `standard`: no allow; `hard`: deny, Stop and plain answers only; never a wider scope; replaces `parent_approvals` and `turn.parent_continue`; a convention for an honest parent, not a security boundary, and the user's choice: set it only when the user asks), `rules:` (list), `disable:` (a rule id or a list of them, `id` or `bundle:id`, switching off a bundle's or config rule without editing it), `small_models` (`auto`, the default: small = 32B or less read from the name; a glob or list of globs; `[]` for none). A rule takes only `id`, `tool`, `command`, `path`, `git`, `models`, `verdict`, `reason`, `scopes`: `id` required; at least one of `tool` (a name, `shell` = execute + task_create, a `File.fnmatch` glob like `"mcp_*"`, or a list), `command` (a Ruby regex on the shell command), `path` (a glob, or `outside_repo`: outside the session's repo, tmp folders and memory files excepted), `git` (only `outside_repo`: a shell call runs commit/add/reset/… in another checkout); `models` (optional: `small`, a model-name glob, or a list; without it the rule is for every model); `verdict` `ask|deny`; `scopes` (for `ask`) a subset of `once, session, repo, rule`. **Any parse error (an unknown key, a bad regex, no verdict) makes chi deny every tool call** until fixed, so validate with `YAML.safe_load` and keep the list shape. Rules are read again on the next tool call after config.yml or a bundle's rules change: no restart needed. Installed bundles' rule files (`chi bundle install guardrails`) add to them; `/guardrails` lists what loaded.
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: samagotchi-system
|
|
3
|
-
version: 0.
|
|
3
|
+
version: 0.182.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:
|
|
7
7
|
identity.md: sha256:29c2f7df9f6c5acbc5ec17000a4490741e55e426af15ca0d81c8706edd9bd027
|
|
8
8
|
self_map.md: sha256:750822b3488b302c6e32638e6224f270d8e06b50ea85cd6e0bb5a6ff12eed1d8
|
|
9
|
-
config_modification_protocol.md: sha256:
|
|
9
|
+
config_modification_protocol.md: sha256:7bced9b4e03f50c215e1c0bb786a9bfb51f5c1b71ace961ba16ccf6890270f72
|
|
10
10
|
memory_guide.md: sha256:272443ff8292631b28239cb8431d6e8dd19aa23fc53d05e1a10c11696a0a5d8d
|
|
11
11
|
delegated.md: sha256:a0d6ddcd4a8be06526d964898611775fd251cfd9d145a9d16afaccaa503597bd
|
data/lib/samagotchi/client.rb
CHANGED
|
@@ -126,6 +126,8 @@ module Samagotchi
|
|
|
126
126
|
# @param scheme [String, nil] "https" for a TLS server (default http)
|
|
127
127
|
# @param first_token_timeout [Numeric, nil] seconds a completion may take
|
|
128
128
|
# to stream its first text (LLM::HTTP); nil: no limit
|
|
129
|
+
# @param stream_idle_timeout [Numeric, nil] seconds a completion that
|
|
130
|
+
# streamed text may go without more (LLM::HTTP); nil: no limit
|
|
129
131
|
# @param name [String, nil] the host's config name, for error lines
|
|
130
132
|
# (default: LABEL)
|
|
131
133
|
# @param api_key_env [String, nil] the variable holding the host's API
|
|
@@ -135,7 +137,7 @@ module Samagotchi
|
|
|
135
137
|
# HostEntry#auth_scheme), nil: Bearer
|
|
136
138
|
# @param env [Hash] where the key variable is read
|
|
137
139
|
def initialize(host: nil, port: nil, open_timeout: nil, read_timeout: nil, sleeper: nil, scheme: nil,
|
|
138
|
-
first_token_timeout: nil, name: nil, api_key_env: nil, auth: nil, env: ENV)
|
|
140
|
+
first_token_timeout: nil, stream_idle_timeout: nil, name: nil, api_key_env: nil, auth: nil, env: ENV)
|
|
139
141
|
# Unified config precedence: CLI > ENV > file > default (via Samagotchi::Config)
|
|
140
142
|
@host = host || Samagotchi::Config.get("server.host")
|
|
141
143
|
@port = (port || Samagotchi::Config.get("server.port")).to_i
|
|
@@ -150,16 +152,21 @@ module Samagotchi
|
|
|
150
152
|
@props_failures = @props_entry[:failures]
|
|
151
153
|
@props_mutex = @props_entry[:mutex]
|
|
152
154
|
@first_token_timeout = first_token_timeout
|
|
155
|
+
@stream_idle_timeout = stream_idle_timeout
|
|
153
156
|
@host_name = name
|
|
154
157
|
@label = name.to_s.empty? ? LABEL : name.to_s
|
|
155
158
|
@http = LLM::HTTP.new(label: @label, open_timeout: @open_timeout, read_timeout: @read_timeout,
|
|
156
159
|
sleeper: sleeper, first_token_timeout: first_token_timeout,
|
|
160
|
+
stream_idle_timeout: stream_idle_timeout,
|
|
157
161
|
api_key: LLM::ApiKey.for(api_key_env, host: @label, env: env, scheme: auth))
|
|
158
162
|
end
|
|
159
163
|
|
|
160
164
|
# Seconds a completion may take to stream its first text, or nil.
|
|
161
165
|
attr_reader :first_token_timeout
|
|
162
166
|
|
|
167
|
+
# Seconds a completion that streamed text may go without more, or nil.
|
|
168
|
+
attr_reader :stream_idle_timeout
|
|
169
|
+
|
|
163
170
|
# The host's config name, or nil when built without one.
|
|
164
171
|
attr_reader :host_name
|
|
165
172
|
|
data/lib/samagotchi/config.rb
CHANGED
|
@@ -112,6 +112,11 @@ module Samagotchi
|
|
|
112
112
|
# or tool call, for every host; 0 = off. Unset: 120 on remote hosts,
|
|
113
113
|
# off on local ones. hosts.<name>.first_token_timeout wins.
|
|
114
114
|
Entry.new(key: "server.first_token_timeout", yaml_path: %w[server first_token_timeout], type: :integer, default: nil, expose: %i[env config], lifecycle: :worker_start),
|
|
115
|
+
# Seconds a streamed answer that showed something may go without
|
|
116
|
+
# showing more (keep-alives don't count), for every host; 0 = off.
|
|
117
|
+
# Unset: 120 on remote hosts, off on local ones.
|
|
118
|
+
# hosts.<name>.stream_idle_timeout wins.
|
|
119
|
+
Entry.new(key: "server.stream_idle_timeout", yaml_path: %w[server stream_idle_timeout], type: :integer, default: nil, expose: %i[env config], lifecycle: :worker_start),
|
|
115
120
|
|
|
116
121
|
# Both session-settable (chi --set recap.enabled=false): RecapSetup reads them through the session's layer.
|
|
117
122
|
Entry.new(key: "recap.enabled", yaml_path: %w[recap enabled], type: :bool, default: nil, expose: %i[env config], lifecycle: :worker_start,
|
|
@@ -394,6 +399,9 @@ module Samagotchi
|
|
|
394
399
|
# Opt-in: the page checks each finished turn against a reload of it (one full read per turn end) and chi web logs
|
|
395
400
|
# reload_checked, with reload_mismatch and the kinds that differed (counts only, no content).
|
|
396
401
|
Entry.new(key: "web.reload_check", yaml_path: %w[web reload_check], type: :bool, default: false, expose: %i[env config cli], lifecycle: :web_start),
|
|
402
|
+
# auto: a block the owner's page can't draw in the newest answer (a chi-ui picks, a bundle's diagram) is asked
|
|
403
|
+
# for again once, on the side, and the answer patched (docs/internals/block-renderers.md); off: it stays source.
|
|
404
|
+
Entry.new(key: "web.block_fix", yaml_path: %w[web block_fix], type: :enum, default: "auto", expose: %i[env config], enum_values: %w[auto off], lifecycle: :web_start),
|
|
397
405
|
# Quick replies next to Annotate in the page's selection bubble, "|"-separated (a YAML list works too); "" leaves only Annotate.
|
|
398
406
|
Entry.new(key: "web.annotate_presets", yaml_path: %w[web annotate_presets], type: :string, default: "Agreed|Could you please elaborate?", expose: %i[env config cli], lifecycle: :web_start),
|
|
399
407
|
# What a file ref (a tool row's file, a diff line) opens on this machine: a preset (vscode, vscode-insiders, cursor, zed, none) or a URL template with {path} and an optional {line} (Web::Editor).
|
|
@@ -431,7 +439,7 @@ module Samagotchi
|
|
|
431
439
|
# Maps of named entries and the keys an entry may hold
|
|
432
440
|
# (HostConfig.all, ModelSettings.all).
|
|
433
441
|
MAP_ENTRY_KEYS = {
|
|
434
|
-
"hosts" => %w[host port url api api_key_env auth dialect profile first_token_timeout vision sampling thinking
|
|
442
|
+
"hosts" => %w[host port url api api_key_env auth dialect profile first_token_timeout stream_idle_timeout vision sampling thinking
|
|
435
443
|
reasoning_history enabled remote window_tokens steer_cut_after llm_context_strategy llm_context_apply llm_context_budget_tokens models].freeze,
|
|
436
444
|
"models" => %w[profile vision sampling thinking reasoning_history window_tokens steer_cut_after llm_context_strategy llm_context_apply
|
|
437
445
|
llm_context_budget_tokens].freeze
|
|
@@ -82,6 +82,14 @@ module Samagotchi
|
|
|
82
82
|
end
|
|
83
83
|
end
|
|
84
84
|
|
|
85
|
+
# Whether +id+'s continue lock is held now, without creating its
|
|
86
|
+
# session folder or lock file. Read-only callers use this for a preview.
|
|
87
|
+
def lock_held?(id, state_dir:)
|
|
88
|
+
return false unless Session.valid_id?(id)
|
|
89
|
+
|
|
90
|
+
locked?(File.join(Session.session_dir(id, state_dir: state_dir), LOCK))
|
|
91
|
+
end
|
|
92
|
+
|
|
85
93
|
# Whether a continue holds the lock at +path+: a shared try that fails.
|
|
86
94
|
# The try is let go at once (the file is closed).
|
|
87
95
|
def locked?(path)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require_relative "bundle_manifest"
|
|
5
|
+
require_relative "installed_bundles"
|
|
6
|
+
require_relative "log"
|
|
7
|
+
require_relative "paths"
|
|
8
|
+
|
|
9
|
+
module Samagotchi
|
|
10
|
+
# A first session's reminder when none of the core profile's members is installed.
|
|
11
|
+
module CoreNotice
|
|
12
|
+
STAMP_FILE = "core_noticed"
|
|
13
|
+
LINE = "chi: the core safety bundles (loop-guard, guardrails, cost-cap…) aren't installed: chi bundle install core"
|
|
14
|
+
CORE_DIR = File.join(__dir__, "bundles", "core")
|
|
15
|
+
|
|
16
|
+
module_function
|
|
17
|
+
|
|
18
|
+
def show(env: ENV, io: $stderr)
|
|
19
|
+
return if env["SAMAGOTCHI_CORE_NOTICE"] == "off" || env.key?("SAMAGOTCHI_PROJECT_ENV")
|
|
20
|
+
|
|
21
|
+
stamp = File.join(Paths.state_dir(env: env), STAMP_FILE)
|
|
22
|
+
return if File.exist?(stamp)
|
|
23
|
+
|
|
24
|
+
members = BundleManifest.read(dir: CORE_DIR).includes
|
|
25
|
+
installed = InstalledBundles.each(dir: MemoryPaths.bundles_dir(env: env)).any? { |name, _| members.include?(name) }
|
|
26
|
+
return if installed
|
|
27
|
+
|
|
28
|
+
FileUtils.mkdir_p(File.dirname(stamp))
|
|
29
|
+
File.open(stamp, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |file|
|
|
30
|
+
io.puts(LINE)
|
|
31
|
+
file.write("shown\n")
|
|
32
|
+
rescue StandardError
|
|
33
|
+
File.unlink(stamp)
|
|
34
|
+
raise
|
|
35
|
+
end
|
|
36
|
+
LINE
|
|
37
|
+
rescue Errno::EEXIST
|
|
38
|
+
nil
|
|
39
|
+
rescue StandardError => e
|
|
40
|
+
Log.warn(:turn, "core_notice_failed", error: e.class.name, msg: e.message)
|
|
41
|
+
nil
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../answer_display"
|
|
4
|
+
require_relative "../answer_tail"
|
|
5
|
+
require_relative "../block_fix"
|
|
6
|
+
require_relative "../bridge/turn_drawings"
|
|
7
|
+
require_relative "../log"
|
|
8
|
+
|
|
9
|
+
module Samagotchi
|
|
10
|
+
class Engine
|
|
11
|
+
# A failed block asked for again (docs/internals/block-renderers.md, A
|
|
12
|
+
# failed block is asked for again). #fix_block answers the Bridge's
|
|
13
|
+
# route and starts the side request; its result waits in
|
|
14
|
+
# @block_fix_ready until the worker's loop, between turns, calls
|
|
15
|
+
# #apply_block_fixes, which writes the conversation: the answer's text
|
|
16
|
+
# when no turn started since the ask and it is still the newest answer,
|
|
17
|
+
# else its display only, or nothing when the answer is gone.
|
|
18
|
+
# Writes @block_fix_running, @block_fix_ready, @block_fix_turns (under
|
|
19
|
+
# @block_fix_mutex; the counter on the turn thread), reads @session,
|
|
20
|
+
# @side_judgments, @session_observer.
|
|
21
|
+
module BlockFixPart
|
|
22
|
+
# What a pending result knows of its answer: its place in the
|
|
23
|
+
# conversation, its digest then (Bridge::TurnDrawings.digest), and the
|
|
24
|
+
# turn counter then (nil: a turn was running as it was asked).
|
|
25
|
+
Anchor = Data.define(:index, :digest, :turns)
|
|
26
|
+
MOVED_DIGEST_LIMIT = 64
|
|
27
|
+
# A finished ask: +fixed+ (the new source) or +reason+ (why not).
|
|
28
|
+
Result = Data.define(:turn_id, :lang, :key, :source, :fixed, :reason, :anchor, :started) do
|
|
29
|
+
def fixed? = !fixed.nil?
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# The worker's wake (Waker#wake), called once a result waits: an idle
|
|
33
|
+
# worker applies it at once. nil (the default): nothing is woken.
|
|
34
|
+
def block_fix_ready=(callback)
|
|
35
|
+
@block_fix_wake = callback
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# The Bridge's POST blocks/fix: whether +source+, a +lang+ block of
|
|
39
|
+
# +turn_id+'s answer, is asked for again.
|
|
40
|
+
# @return [Array(Integer, Hash)] the status and the body: 200
|
|
41
|
+
# {state: "fixed" | "failed", reason:} (asked before), 202
|
|
42
|
+
# {state: "running"}, or an error ({error:, detail:}: 409
|
|
43
|
+
# fix_unavailable / block_not_found, 413 block_too_large, 429
|
|
44
|
+
# fix_limit (BlockFix::PER_ANSWER) / fix_busy)
|
|
45
|
+
def fix_block(turn_id:, lang:, source:, reason:)
|
|
46
|
+
session = @session
|
|
47
|
+
return block_fix_refused(409, :fix_unavailable) if session.nil? || session.scratch || !BlockFix.available?
|
|
48
|
+
return block_fix_refused(413, :block_too_large) if source.to_s.bytesize > BlockFix::MAX_SOURCE_BYTES
|
|
49
|
+
|
|
50
|
+
# The counter before the running flag: a turn sets the flag, then
|
|
51
|
+
# counts (#note_block_fix_turn), so one starting between the reads
|
|
52
|
+
# still shows as a change. The running turn ending with this answer
|
|
53
|
+
# (the page asks on its end event, before its hooks are done) is no
|
|
54
|
+
# turn since; any other running turn is.
|
|
55
|
+
turns = @block_fix_turns
|
|
56
|
+
turns = nil if turn_running? && turn_context&.id.to_s != turn_id.to_s
|
|
57
|
+
messages = session.messages
|
|
58
|
+
answer = AnswerTail.find(messages, turn_id: turn_id)
|
|
59
|
+
index = answer && messages.index { |message| message.equal?(answer) }
|
|
60
|
+
return block_fix_refused(409, :block_not_found) unless index
|
|
61
|
+
|
|
62
|
+
key = BlockFix.key(lang, source)
|
|
63
|
+
shown = !BlockFix.locate(block_fix_shown(answer), lang: lang, source: source).nil?
|
|
64
|
+
# The stamp before the text: a page that drew the answer before its
|
|
65
|
+
# fix (a second tab) asks for a block no longer in it, and is told
|
|
66
|
+
# fixed (it reads the answer again).
|
|
67
|
+
known = BlockFix.stamp_for(answer, key)
|
|
68
|
+
return [200, block_fix_known(known, key, shown: shown)] if known
|
|
69
|
+
return block_fix_refused(409, :block_not_found) unless shown
|
|
70
|
+
|
|
71
|
+
# In flight per answer and block: the same block in a newer answer
|
|
72
|
+
# is that answer's own ask (its result lands in it, its event names it).
|
|
73
|
+
asking = [index, key]
|
|
74
|
+
@block_fix_mutex.synchronize do
|
|
75
|
+
return [202, { state: "running" }] if block_fix_pending?(asking)
|
|
76
|
+
return block_fix_refused(429, :fix_limit) if block_fix_asked(answer, index) >= BlockFix::PER_ANSWER
|
|
77
|
+
return block_fix_refused(429, :fix_busy) if @block_fix_running.size >= BlockFix::MAX_RUNNING
|
|
78
|
+
|
|
79
|
+
@block_fix_running << asking
|
|
80
|
+
end
|
|
81
|
+
anchor = Anchor.new(index: index, digest: Bridge::TurnDrawings.digest(answer), turns: turns)
|
|
82
|
+
conversation = AnswerDisplay.strip_all(messages[0..index])
|
|
83
|
+
Log.info(:model, "block_fix_asked", lang: lang, key: key, bytes: source.to_s.bytesize)
|
|
84
|
+
start_block_fix(conversation, turn_id: turn_id.to_s, lang: lang.to_s, key: key, source: source.to_s,
|
|
85
|
+
reason: reason.to_s, anchor: anchor)
|
|
86
|
+
[202, { state: "running" }]
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# The results waiting, applied: on the worker's loop, between turns
|
|
90
|
+
# (a running turn holds its own copy of the conversation and writes it
|
|
91
|
+
# back at its end). The caller saves the session when this is > 0.
|
|
92
|
+
# @return [Integer] how many changed the conversation
|
|
93
|
+
def apply_block_fixes
|
|
94
|
+
return 0 if turn_running? || @session.nil?
|
|
95
|
+
|
|
96
|
+
ready = @block_fix_mutex.synchronize { @block_fix_ready.slice!(0..) }
|
|
97
|
+
return 0 if ready.empty?
|
|
98
|
+
|
|
99
|
+
synchronize_events { ready.count { |result| apply_block_fix(@session, result) } }
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# The block fix's [answer index, key] pairs still asked for (specs).
|
|
103
|
+
def block_fixes_running = @block_fix_mutex.synchronize { @block_fix_running.dup }
|
|
104
|
+
|
|
105
|
+
private
|
|
106
|
+
|
|
107
|
+
def init_block_fix
|
|
108
|
+
@block_fix_mutex = Mutex.new
|
|
109
|
+
@block_fix_running = []
|
|
110
|
+
@block_fix_ready = []
|
|
111
|
+
@block_fix_turns = 0
|
|
112
|
+
@block_fix_wake = nil
|
|
113
|
+
# An answer's digest before a fix in its text => after (on the loop
|
|
114
|
+
# thread): the other block of the same answer, asked before that fix
|
|
115
|
+
# landed, still knows its answer.
|
|
116
|
+
@block_fix_moved = {}
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
# A turn takes its messages (#turn_messages): a fix asked before it
|
|
120
|
+
# lands in the answer's display only.
|
|
121
|
+
def note_block_fix_turn
|
|
122
|
+
@block_fix_turns += 1
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# Whether [answer index, key] is asked for or its result waits (under
|
|
126
|
+
# @block_fix_mutex).
|
|
127
|
+
def block_fix_pending?(asking)
|
|
128
|
+
@block_fix_running.include?(asking) || @block_fix_ready.any? { |r| [r.anchor.index, r.key] == asking }
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# How many blocks of the answer at +index+ were asked for: its stamp's
|
|
132
|
+
# and those in flight or waiting (under @block_fix_mutex). The stamp
|
|
133
|
+
# is on the message, so the count holds across a page's reload.
|
|
134
|
+
def block_fix_asked(answer, index)
|
|
135
|
+
keys = BlockFix.stamps(answer).map { |entry| entry[:key] }
|
|
136
|
+
keys += @block_fix_running.filter_map { |at, key| key if at == index }
|
|
137
|
+
keys += @block_fix_ready.filter_map { |r| r.key if r.anchor.index == index }
|
|
138
|
+
keys.uniq.size
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def block_fix_refused(status, code)
|
|
142
|
+
[status, { error: code.to_s, detail: BlockFix::REFUSALS.fetch(code) }]
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# A block the answer's stamp knows: asked before. A block that is the
|
|
146
|
+
# fix of an earlier one fails again: failed, whatever that fix was. A
|
|
147
|
+
# fixed block still +shown+ (a copy the fix couldn't reach) is failed
|
|
148
|
+
# too: "fixed" would have the page read the answer again, draw the
|
|
149
|
+
# copy, fail it and ask again, with no end.
|
|
150
|
+
def block_fix_known(entry, key, shown:)
|
|
151
|
+
return { state: "failed", reason: "it failed again after a fix" } if entry[:fixed_key] == key && entry[:key] != key
|
|
152
|
+
return { state: "failed", reason: "a copy of it is still in the answer" } if entry[:state].to_s == "fixed" && shown
|
|
153
|
+
|
|
154
|
+
{ state: entry[:state].to_s, reason: entry[:reason] }.compact
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# The text the page draws an answer from.
|
|
158
|
+
def block_fix_shown(message)
|
|
159
|
+
(message[AnswerDisplay::KEY] || message[AnswerDisplay::KEY.to_s] || message[:content] || message["content"]).to_s
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
def start_block_fix(conversation, **job)
|
|
163
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
164
|
+
warn = ->(error) { Log.warn(:model, "block_fix_thread_failed", error: error.class.name, msg: error.message.to_s[0, 200]) }
|
|
165
|
+
@side_judgments.aside(warn: warn) do
|
|
166
|
+
result = begin
|
|
167
|
+
ask_block_fix(conversation, **job, started: started)
|
|
168
|
+
rescue StandardError => e
|
|
169
|
+
Result.new(**job.except(:reason), started: started, fixed: nil,
|
|
170
|
+
reason: e.message.to_s.lines.first.to_s.strip[0, 200])
|
|
171
|
+
end
|
|
172
|
+
@block_fix_mutex.synchronize do
|
|
173
|
+
@block_fix_running.delete([job[:anchor].index, job[:key]])
|
|
174
|
+
@block_fix_ready << result
|
|
175
|
+
end
|
|
176
|
+
@block_fix_wake&.call
|
|
177
|
+
end
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
def ask_block_fix(conversation, turn_id:, lang:, key:, source:, reason:, anchor:, started:)
|
|
181
|
+
request = BlockFix.request(messages: conversation, lang: lang, source: source, reason: reason)
|
|
182
|
+
answer = ask_side_model(request, timeout: BlockFix::TIMEOUT_SECONDS, max_tokens: BlockFix::MAX_TOKENS,
|
|
183
|
+
cancel_controller: nil, source: BlockFix::SOURCE, whole: true)
|
|
184
|
+
extracted = BlockFix.extract(answer.text, cut_off: answer.cut_off, failed: source)
|
|
185
|
+
refusal = extracted.refusal || BlockFix.check(lang: lang, source: extracted.source)
|
|
186
|
+
Result.new(turn_id: turn_id, lang: lang, key: key, source: source, anchor: anchor, started: started,
|
|
187
|
+
fixed: refusal ? nil : extracted.source, reason: refusal)
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
# One result, under the event lock.
|
|
191
|
+
# @return [Boolean] whether the conversation changed
|
|
192
|
+
# A fix that can't land in an answer still there (its shown text lost
|
|
193
|
+
# the block, or the fix would pass the display's size) stamps it
|
|
194
|
+
# failed with the reason, so a reload doesn't ask again; only a gone
|
|
195
|
+
# or changed answer is dropped, with no stamp.
|
|
196
|
+
def apply_block_fix(session, result)
|
|
197
|
+
messages = session.messages
|
|
198
|
+
answer = messages[result.anchor.index]
|
|
199
|
+
return block_fix_dropped(result, "the answer changed") unless answer && block_fix_anchored?(messages, answer, result)
|
|
200
|
+
|
|
201
|
+
unless BlockFix.locate(block_fix_shown(answer), lang: result.lang, source: result.source)
|
|
202
|
+
result = result.with(fixed: nil, reason: "the answer changed")
|
|
203
|
+
end
|
|
204
|
+
copy, landed = block_fix_patched(messages, answer, result)
|
|
205
|
+
unless copy
|
|
206
|
+
result = result.with(fixed: nil, reason: "the fix is too long")
|
|
207
|
+
copy, landed = block_fix_patched(messages, answer, result)
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
list = messages.dup
|
|
211
|
+
list[result.anchor.index] = copy
|
|
212
|
+
replace_session_messages(session, list)
|
|
213
|
+
was = Bridge::TurnDrawings.digest(answer)
|
|
214
|
+
now = Bridge::TurnDrawings.digest(copy)
|
|
215
|
+
if was != now
|
|
216
|
+
@block_fix_moved.delete(was)
|
|
217
|
+
@block_fix_moved[was] = now
|
|
218
|
+
@block_fix_moved.shift while @block_fix_moved.size > MOVED_DIGEST_LIMIT
|
|
219
|
+
end
|
|
220
|
+
block_fix_announce(result, state: result.fixed? ? "fixed" : "failed", landed: landed, was_digest: was, digest: now)
|
|
221
|
+
true
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
# Still the message asked about: the same digest, and still the one
|
|
225
|
+
# the turn id names (a reminder turn's id names no prompt, so it falls
|
|
226
|
+
# back to the newest answer, which a later turn's answer becomes).
|
|
227
|
+
def block_fix_anchored?(messages, answer, result)
|
|
228
|
+
Bridge::TurnDrawings.digest(answer) == block_fix_digest_now(result.anchor.digest) &&
|
|
229
|
+
AnswerTail.find(messages, turn_id: result.turn_id).equal?(answer)
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
# +digest+ after the fixes that landed in its answer's text since.
|
|
233
|
+
def block_fix_digest_now(digest)
|
|
234
|
+
seen = []
|
|
235
|
+
while (moved = @block_fix_moved[digest]) && !seen.include?(digest)
|
|
236
|
+
seen << digest
|
|
237
|
+
digest = moved
|
|
238
|
+
end
|
|
239
|
+
digest
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
# The answer's copy with the fix (or, for a failed ask, only the stamp)
|
|
243
|
+
# and where it landed ("answer", "display", nil); nil copy: refused.
|
|
244
|
+
def block_fix_patched(messages, answer, result)
|
|
245
|
+
unless result.fixed?
|
|
246
|
+
entry = BlockFix.entry(key: result.key, state: "failed", reason: result.reason)
|
|
247
|
+
return [BlockFix.with_stamp(answer, entry), nil]
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
copy, landed = if result.anchor.turns == @block_fix_turns && AnswerTail.find(messages).equal?(answer)
|
|
251
|
+
block_fix_in_answer(answer, result)
|
|
252
|
+
else
|
|
253
|
+
block_fix_in_display(answer, result)
|
|
254
|
+
end
|
|
255
|
+
return [nil, nil] unless copy
|
|
256
|
+
|
|
257
|
+
entry = BlockFix.entry(key: result.key, fixed_key: BlockFix.key(result.lang, result.fixed), state: "fixed")
|
|
258
|
+
[BlockFix.with_stamp(copy, entry), landed]
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
# No turn since, the newest answer: its text (and its display, and
|
|
262
|
+
# on api: anthropic its saved blocks) holds the fix, in every copy of
|
|
263
|
+
# the block; nil copy: the display would pass its size.
|
|
264
|
+
def block_fix_in_answer(answer, result)
|
|
265
|
+
content = answer[:content].to_s
|
|
266
|
+
places = BlockFix.locate_all(content, lang: result.lang, source: result.source)
|
|
267
|
+
return block_fix_in_display(answer, result) if places.empty?
|
|
268
|
+
|
|
269
|
+
copy = answer.merge(content: BlockFix.replace_all(content, places, result.fixed))
|
|
270
|
+
if (display = answer[AnswerDisplay::KEY])
|
|
271
|
+
shown = BlockFix.locate_all(display, lang: result.lang, source: result.source)
|
|
272
|
+
text = shown.empty? ? display : BlockFix.replace_all(display, shown, result.fixed)
|
|
273
|
+
# The display's own cap (AnswerDisplay::MAX_CHARS), as #block_fix_in_display keeps it.
|
|
274
|
+
return [nil, nil] if text.length > AnswerDisplay::MAX_CHARS
|
|
275
|
+
|
|
276
|
+
copy[AnswerDisplay::KEY] = text
|
|
277
|
+
end
|
|
278
|
+
[block_fix_blocks(copy, result, places.size), "answer"]
|
|
279
|
+
end
|
|
280
|
+
|
|
281
|
+
# A turn since: only what the page renders (`display`), never what a
|
|
282
|
+
# model was sent.
|
|
283
|
+
def block_fix_in_display(answer, result)
|
|
284
|
+
shown = block_fix_shown(answer)
|
|
285
|
+
places = BlockFix.locate_all(shown, lang: result.lang, source: result.source)
|
|
286
|
+
return [nil, nil] if places.empty?
|
|
287
|
+
|
|
288
|
+
text = BlockFix.replace_all(shown, places, result.fixed)
|
|
289
|
+
return [nil, nil] if text.length > AnswerDisplay::MAX_CHARS
|
|
290
|
+
|
|
291
|
+
[answer.merge(AnswerDisplay::KEY => text), "display"]
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
# The saved Messages-API blocks (anthropic_content), which
|
|
295
|
+
# AnthropicWire sends as they are: the text blocks holding the
|
|
296
|
+
# +copies+ the text had patched, or the blocks dropped (the answer goes
|
|
297
|
+
# as its text) when they don't hold every copy whole. A thinking block
|
|
298
|
+
# is never touched.
|
|
299
|
+
def block_fix_blocks(copy, result, copies)
|
|
300
|
+
blocks = copy[:anthropic_content]
|
|
301
|
+
return copy unless blocks.is_a?(Array) && !blocks.empty?
|
|
302
|
+
|
|
303
|
+
found = 0
|
|
304
|
+
patched = blocks.map do |block|
|
|
305
|
+
next block if !block.is_a?(Hash) || (block["type"] || block[:type]).to_s != "text"
|
|
306
|
+
|
|
307
|
+
text_key = block.key?("text") ? "text" : :text
|
|
308
|
+
places = BlockFix.locate_all(block[text_key].to_s, lang: result.lang, source: result.source)
|
|
309
|
+
next block if places.empty?
|
|
310
|
+
|
|
311
|
+
found += places.size
|
|
312
|
+
block.merge(text_key => BlockFix.replace_all(block[text_key].to_s, places, result.fixed))
|
|
313
|
+
end
|
|
314
|
+
found == copies ? copy.merge(anthropic_content: patched) : copy.except(:anthropic_content)
|
|
315
|
+
end
|
|
316
|
+
|
|
317
|
+
def block_fix_dropped(result, why)
|
|
318
|
+
block_fix_announce(result, state: "dropped", landed: nil, reason: why)
|
|
319
|
+
false
|
|
320
|
+
end
|
|
321
|
+
|
|
322
|
+
def block_fix_announce(result, state:, landed:, reason: result.reason, was_digest: nil, digest: nil)
|
|
323
|
+
ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - result.started) * 1000).round
|
|
324
|
+
Log.info(:model, "block_fix_#{state}", lang: result.lang, key: result.key, bytes: result.fixed.to_s.bytesize,
|
|
325
|
+
ms: ms, landed: landed, reason: reason)
|
|
326
|
+
@session_observer.notify({ type: :block_fix, turn_id: result.turn_id, key: result.key, lang: result.lang,
|
|
327
|
+
state: state, landed: landed, reason: reason, was_digest: was_digest,
|
|
328
|
+
digest: digest }.compact)
|
|
329
|
+
end
|
|
330
|
+
end
|
|
331
|
+
end
|
|
332
|
+
end
|