samagotchi 0.194.0 → 0.196.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +80 -1
- data/docs/architecture.md +2 -1
- data/docs/bundle-authoring.md +23 -23
- data/docs/bundles.md +201 -7
- data/docs/cli.md +5 -1
- data/docs/configuration.md +25 -4
- data/docs/context.md +13 -3
- data/docs/guardrails.md +6 -4
- data/docs/hooks.md +3 -1
- data/docs/internals/attached-context.md +2 -0
- data/docs/internals/block-renderers.md +4 -1
- data/docs/internals/bridge.md +4 -0
- data/docs/internals/engine.md +15 -2
- data/docs/internals/knowledge.md +215 -0
- data/docs/internals/pages.md +17 -9
- data/docs/internals/panes.md +51 -13
- data/docs/internals/participants.md +15 -3
- data/docs/internals/peers.md +14 -9
- data/docs/internals/session-lifecycle.md +26 -12
- data/docs/internals/web-frontend.md +64 -27
- data/docs/memory.md +4 -2
- data/docs/pages.md +72 -1
- data/docs/peers.md +25 -14
- data/docs/plugins.md +132 -6
- data/docs/releasing.md +1 -1
- data/docs/scheduling.md +4 -0
- data/docs/sessions.md +9 -2
- data/docs/system-one.md +3 -1
- data/docs/testing.md +3 -1
- data/lib/samagotchi/bundle_manifest.rb +30 -5
- data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
- data/lib/samagotchi/bundles/claude-peer/plugin.rb +2 -2
- data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
- data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
- data/lib/samagotchi/bundles/coordinator/manifest.yml +7 -4
- data/lib/samagotchi/bundles/coordinator/plugin.rb +15 -5
- data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +10 -0
- data/lib/samagotchi/bundles/core/manifest.yml +2 -2
- data/lib/samagotchi/bundles/cost-cap/manifest.yml +4 -4
- data/lib/samagotchi/bundles/cost-cap/plugin.rb +54 -3
- data/lib/samagotchi/bundles/dev/manifest.yml +3 -2
- data/lib/samagotchi/bundles/github-pr/manifest.yml +4 -2
- data/lib/samagotchi/bundles/knowledge/adapters.rb +205 -0
- data/lib/samagotchi/bundles/knowledge/catalog.rb +151 -0
- data/lib/samagotchi/bundles/knowledge/chi_adapters.rb +178 -0
- data/lib/samagotchi/bundles/knowledge/chunker.rb +55 -0
- data/lib/samagotchi/bundles/knowledge/github.rb +246 -0
- data/lib/samagotchi/bundles/knowledge/manifest.yml +27 -0
- data/lib/samagotchi/bundles/knowledge/plugin.rb +807 -0
- data/lib/samagotchi/bundles/knowledge/query.rb +30 -0
- data/lib/samagotchi/bundles/knowledge/query_log.rb +55 -0
- data/lib/samagotchi/bundles/knowledge/refresh.rb +133 -0
- data/lib/samagotchi/bundles/knowledge/store.rb +264 -0
- data/lib/samagotchi/bundles/reflect/manifest.yml +17 -0
- data/lib/samagotchi/bundles/reflect/scripts/reflect.rb +439 -0
- data/lib/samagotchi/bundles/reflect/skill_reflect.md +100 -0
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/context_change.rb +44 -0
- data/lib/samagotchi/context_note.rb +1 -1
- data/lib/samagotchi/context_providers.rb +14 -0
- data/lib/samagotchi/context_sources.rb +3 -25
- data/lib/samagotchi/engine/plugins.rb +21 -0
- data/lib/samagotchi/events.rb +1 -0
- data/lib/samagotchi/guardrails/pair_boundary.rb +12 -4
- data/lib/samagotchi/guardrails/review_paths.rb +13 -3
- data/lib/samagotchi/guardrails/targets.rb +24 -2
- data/lib/samagotchi/guardrails_command.rb +3 -9
- data/lib/samagotchi/hook_label.rb +19 -0
- data/lib/samagotchi/hook_routes.rb +3 -2
- data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
- data/lib/samagotchi/memory_bundle/builder.rb +2 -1
- data/lib/samagotchi/memory_bundle/installed_copy.rb +2 -1
- data/lib/samagotchi/page_command.rb +90 -6
- data/lib/samagotchi/pages/launch.rb +16 -8
- data/lib/samagotchi/pages/runner.rb +7 -2
- data/lib/samagotchi/pages/runtime.rb +62 -2
- data/lib/samagotchi/pages.rb +4 -0
- data/lib/samagotchi/panes/kitty.rb +20 -5
- data/lib/samagotchi/panes.rb +81 -12
- data/lib/samagotchi/participants.rb +17 -6
- data/lib/samagotchi/peer_exchanges.rb +1 -2
- data/lib/samagotchi/peer_note.rb +38 -5
- data/lib/samagotchi/peer_presence.rb +20 -7
- data/lib/samagotchi/plugin/api.rb +11 -1
- data/lib/samagotchi/plugin/attached_context.rb +46 -1
- data/lib/samagotchi/plugin/chips.rb +125 -0
- data/lib/samagotchi/plugin/context.rb +43 -8
- data/lib/samagotchi/plugin/panes.rb +52 -9
- data/lib/samagotchi/plugin/peer_pairing.rb +2 -2
- data/lib/samagotchi/plugin/peer_start.rb +61 -36
- data/lib/samagotchi/plugin/peers.rb +6 -3
- data/lib/samagotchi/plugin/project.rb +63 -0
- data/lib/samagotchi/plugin/sessions.rb +36 -1
- data/lib/samagotchi/plugin/tool_spec.rb +28 -9
- data/lib/samagotchi/schedules.rb +8 -2
- data/lib/samagotchi/session.rb +22 -9
- data/lib/samagotchi/session_access/local.rb +34 -33
- data/lib/samagotchi/session_chain/sharing.rb +79 -0
- data/lib/samagotchi/session_chain/successor.rb +4 -2
- data/lib/samagotchi/session_chips.rb +133 -0
- data/lib/samagotchi/session_inbox_delivery.rb +11 -11
- data/lib/samagotchi/session_manager/emptiness.rb +4 -1
- data/lib/samagotchi/session_observer.rb +1 -1
- data/lib/samagotchi/session_stats.rb +437 -0
- data/lib/samagotchi/session_stores.rb +3 -0
- data/lib/samagotchi/session_window.rb +30 -0
- data/lib/samagotchi/speaker.rb +228 -0
- data/lib/samagotchi/steer.rb +36 -132
- data/lib/samagotchi/system_one/approval_choice.rb +22 -0
- data/lib/samagotchi/system_one/approval_label.rb +4 -6
- data/lib/samagotchi/system_prompt.rb +3 -1
- data/lib/samagotchi/terminal_ui/attach_launcher.rb +30 -0
- data/lib/samagotchi/testing/boundary.rb +17 -4
- data/lib/samagotchi/testing/bundle.rb +5 -0
- data/lib/samagotchi/testing/host.rb +1 -0
- data/lib/samagotchi/testing/recorder.rb +10 -0
- data/lib/samagotchi/testing/sessions.rb +11 -3
- data/lib/samagotchi/toolkit.rb +11 -4
- data/lib/samagotchi/toolkit_report_command.rb +14 -18
- data/lib/samagotchi/toolkit_suggest.rb +9 -2
- data/lib/samagotchi/tools/registry.rb +48 -18
- data/lib/samagotchi/tools/tool_index.rb +6 -2
- data/lib/samagotchi/turn_excerpts.rb +302 -0
- data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +9 -0
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +21 -10
- data/lib/samagotchi/web/participant_view.rb +1 -1
- data/lib/samagotchi/web/peer_routes.rb +5 -2
- data/lib/samagotchi/web/plugin_chip_rows.rb +39 -0
- data/lib/samagotchi/web/public/agent_rows.js +1 -0
- data/lib/samagotchi/web/public/app.js +17 -25
- data/lib/samagotchi/web/public/chains.js +0 -26
- data/lib/samagotchi/web/public/command_list.js +2 -3
- data/lib/samagotchi/web/public/composer.js +2 -3
- data/lib/samagotchi/web/public/composer_mount.js +3 -6
- data/lib/samagotchi/web/public/context_chips.js +240 -93
- data/lib/samagotchi/web/public/context_groups.js +84 -0
- data/lib/samagotchi/web/public/draft_follow.js +33 -0
- data/lib/samagotchi/web/public/drafts.js +26 -22
- data/lib/samagotchi/web/public/index.html +32 -0
- data/lib/samagotchi/web/public/peer_chip_kind.js +49 -0
- data/lib/samagotchi/web/public/peer_note.js +2 -2
- data/lib/samagotchi/web/public/peer_row.js +10 -5
- data/lib/samagotchi/web/public/peer_wait.js +4 -2
- data/lib/samagotchi/web/public/plugin_chip.js +55 -0
- data/lib/samagotchi/web/public/plugin_chip_kind.js +48 -0
- data/lib/samagotchi/web/public/send_turn.js +8 -21
- data/lib/samagotchi/web/public/session_actions.js +10 -23
- data/lib/samagotchi/web/public/session_view.js +7 -3
- data/lib/samagotchi/web/public/stream_handlers.js +2 -0
- metadata +33 -1
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "time"
|
|
5
|
+
require_relative "session"
|
|
6
|
+
require_relative "session_paths"
|
|
7
|
+
require_relative "analytics_file"
|
|
8
|
+
require_relative "bridge/card_store"
|
|
9
|
+
require_relative "client_id"
|
|
10
|
+
require_relative "guardrails/approval"
|
|
11
|
+
require_relative "system_one/approval_choice"
|
|
12
|
+
require_relative "hook_label"
|
|
13
|
+
require_relative "session_window"
|
|
14
|
+
require_relative "model_ref"
|
|
15
|
+
require_relative "message_time"
|
|
16
|
+
require_relative "steer"
|
|
17
|
+
require_relative "speaker"
|
|
18
|
+
require_relative "paths"
|
|
19
|
+
|
|
20
|
+
module Samagotchi
|
|
21
|
+
# How one project's sessions went over the last days, as counts: the reader
|
|
22
|
+
# behind a page's `runtime.sessions` (Pages::Runtime#sessions, docs/pages.md).
|
|
23
|
+
# It reads the files other parts write, read-only and without a lock: the
|
|
24
|
+
# session file (Session.list's summaries, and each message's kind, source,
|
|
25
|
+
# author and time, never its text), analytics.json (SessionMetrics' turn
|
|
26
|
+
# and tool records) and cards.json (Bridge::CardStore's entries, by its
|
|
27
|
+
# constants). Every field is optional, as AnalyticsFile says every reader
|
|
28
|
+
# must treat it: a missing one counts as 0. A file that doesn't read adds
|
|
29
|
+
# 1 to +unreadable+ and the rest counts on.
|
|
30
|
+
#
|
|
31
|
+
# Its values hold counts, ids, times, model names, the project's name and
|
|
32
|
+
# tilded path, failure_kind words and the keys of the name-keyed Hashes:
|
|
33
|
+
# no message text, tool output, command, title or failure message
|
|
34
|
+
# (spec/session_stats_spec.rb's allow-list). TurnExcerpts is the one text
|
|
35
|
+
# reader.
|
|
36
|
+
#
|
|
37
|
+
# The window: the turns that started in the last DAYS days (capped by
|
|
38
|
+
# session.retention_days, SessionWindow), and what belongs to them (tool
|
|
39
|
+
# records and cards by turn id, messages by their own time, a question
|
|
40
|
+
# without a turn id by when it was asked); an entry with neither is left
|
|
41
|
+
# out. At most MAX_SESSIONS sessions (lowered by session.max_count),
|
|
42
|
+
# counted after the project filter.
|
|
43
|
+
module SessionStats
|
|
44
|
+
DAYS = 14
|
|
45
|
+
MAX_SESSIONS = 500
|
|
46
|
+
DAY_SECONDS = 86_400
|
|
47
|
+
|
|
48
|
+
# A failed turn's kind, from its failure line (summary, else message,
|
|
49
|
+
# else error class) by the first rule that matches; "none" when it has
|
|
50
|
+
# no line at all. Only the word is kept, never the line.
|
|
51
|
+
FAILURE_KINDS = %w[host_model_not_found host_rejected host_error timeout host_unreachable context_overflow
|
|
52
|
+
empty_answer other none].freeze
|
|
53
|
+
FAILURE_RULES = [
|
|
54
|
+
["host_model_not_found", /HTTP 404.*not found/i],
|
|
55
|
+
["host_rejected", /HTTP 4\d\d/],
|
|
56
|
+
["host_error", /HTTP 5\d\d/],
|
|
57
|
+
["timeout", /timed? ?out|timeout|first token/i],
|
|
58
|
+
["host_unreachable", /connection refused|ECONNREFUSED|could not connect/i],
|
|
59
|
+
["context_overflow", /context|too long|exceed/i],
|
|
60
|
+
["empty_answer", /empty/i]
|
|
61
|
+
].freeze
|
|
62
|
+
|
|
63
|
+
# Who stopped a canceled turn: you (the user's Stop or Ctrl-C, a
|
|
64
|
+
# participant's cancel included), a hook, the worker going mid-turn
|
|
65
|
+
# (SessionMetrics#running_turn_record's worker_stopped: interrupted,
|
|
66
|
+
# never a cancel), or anything else.
|
|
67
|
+
CANCELS = %w[you hook interrupted other].freeze
|
|
68
|
+
YOU_REASONS = %w[user ctrl_c].freeze
|
|
69
|
+
INTERRUPTED = "worker_stopped"
|
|
70
|
+
|
|
71
|
+
# An approval asked under no rule id.
|
|
72
|
+
NO_RULE = "(no rule)"
|
|
73
|
+
# The counts each rule's approvals get (SessionCounts#approvals_by_rule).
|
|
74
|
+
APPROVAL_COUNTS = %w[asked once wide denied unanswered by_parent].freeze
|
|
75
|
+
|
|
76
|
+
# A project: the root's basename, the root as shown (~ for the home),
|
|
77
|
+
# and how many of its sessions are in the window.
|
|
78
|
+
Project = Data.define(:name, :path, :session_count)
|
|
79
|
+
|
|
80
|
+
# One turn that started in the window. +status+ as saved ("completed",
|
|
81
|
+
# "failed", "canceled"), +cancel+ one of CANCELS (nil when it ran to its
|
|
82
|
+
# end), +cancel_bundle+ the hook's bundle ("hook" when the record names
|
|
83
|
+
# none), +automatic+ an origin no person's, +model+ the model (its ref
|
|
84
|
+
# without the host when the record has no model: a failed turn's),
|
|
85
|
+
# +cost+ reported plus estimated, the tool counts from the turn's tool
|
|
86
|
+
# records, +failure_kind+ one of FAILURE_KINDS (nil unless failed).
|
|
87
|
+
TurnCounts = Data.define(:id, :started_at, :status, :cancel, :cancel_bundle, :automatic, :model, :cost,
|
|
88
|
+
:tool_calls, :tool_errors, :tool_calls_by_tool, :tool_errors_by_tool, :failure_kind,
|
|
89
|
+
:context_used_tokens)
|
|
90
|
+
|
|
91
|
+
# One session: its windowed turns (TurnCounts) and what else it counts
|
|
92
|
+
# in the window. +approvals_by_rule+ is rule => {"asked", "once", "wide",
|
|
93
|
+
# "denied", "unanswered", "by_parent"}; +cards_at_cap+ / +notices_at_cap+
|
|
94
|
+
# say its cards.json holds as many cards (or notices) as it keeps, so
|
|
95
|
+
# those counts are lower bounds; +side_cost+ the side requests' cost, a
|
|
96
|
+
# session total (not windowed); +schedule_id+ the schedule whose chain
|
|
97
|
+
# link it is (system:schedule:<id>), else nil.
|
|
98
|
+
SessionCounts = Data.define(:id, :created_at, :updated_at, :model_name, :delegate, :chain_link, :turns,
|
|
99
|
+
:tool_calls_by_tool, :tool_errors_by_tool, :blocked, :auto_allowed, :mid_turn_lines,
|
|
100
|
+
:steers_by_source, :approvals_by_rule, :cards_at_cap, :hook_notices_by_bundle,
|
|
101
|
+
:notices_at_cap, :context_window, :side_cost, :schedule_id)
|
|
102
|
+
|
|
103
|
+
# What runtime.sessions returns. +project+ nil when no session in the
|
|
104
|
+
# window has one; +picked_by+ "folder" (the folder asked for named it)
|
|
105
|
+
# or "newest" (the newest session a person started); +projects+ the
|
|
106
|
+
# other projects seen, most sessions first; +sessions+ newest updated
|
|
107
|
+
# first; +since+ the window's start (ISO 8601 UTC); +sessions_capped+
|
|
108
|
+
# when more matched than were read; +unreadable+ the files that didn't read.
|
|
109
|
+
Listing = Data.define(:project, :picked_by, :projects, :sessions, :since, :sessions_capped, :unreadable)
|
|
110
|
+
|
|
111
|
+
# The listing step (SessionStats.window): the project's kept summaries
|
|
112
|
+
# (Session.list's, newest updated first) and the full root they share.
|
|
113
|
+
# Core API, not a page value: other readers of "this project's sessions
|
|
114
|
+
# in the window" start here.
|
|
115
|
+
Window = Data.define(:project_root, :project, :picked_by, :projects, :summaries, :since, :capped, :unreadable)
|
|
116
|
+
|
|
117
|
+
module_function
|
|
118
|
+
|
|
119
|
+
# @param project [String, nil] a folder: its project (a worktree's
|
|
120
|
+
# repository, a `chi project init` folder) is read; nil, or a folder in
|
|
121
|
+
# no project, reads the newest session a person started's project
|
|
122
|
+
# @param now [Time]
|
|
123
|
+
# @return [Window]
|
|
124
|
+
def window(project: nil, now: Time.now)
|
|
125
|
+
since = now - (SessionWindow.days(DAYS) * DAY_SECONDS)
|
|
126
|
+
max = SessionWindow.max_sessions(max: MAX_SESSIONS)
|
|
127
|
+
state_dir = Session.default_state_dir
|
|
128
|
+
files = Dir.glob(File.join(state_dir, "*#{SessionPaths::FILE_EXT}")).size
|
|
129
|
+
listed = listing(state_dir: state_dir)
|
|
130
|
+
cache = {}
|
|
131
|
+
kept = keep(listed, :all, cache).select { |s| (at = time(s.updated_at)) && at >= since }
|
|
132
|
+
roots = kept.to_h { |s| [s.id, s.project_root(cache: cache)] }
|
|
133
|
+
root, picked_by = pick_root(project, kept, roots, cache)
|
|
134
|
+
mine = root ? kept.select { |s| roots[s.id] == root } : []
|
|
135
|
+
others = kept.group_by { |s| roots[s.id] }.except(nil, root)
|
|
136
|
+
.map { |other, sessions| project_of(other, sessions.size) }
|
|
137
|
+
.sort_by { |p| [-p.session_count, p.name, p.path] }
|
|
138
|
+
Window.new(project_root: root, project: root && project_of(root, mine.size), picked_by: picked_by,
|
|
139
|
+
projects: others.freeze, summaries: mine.first(max).freeze, since: since.utc.iso8601,
|
|
140
|
+
capped: mine.size > max, unreadable: [files - listed.size, 0].max)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# The saved sessions a reader of "this project's sessions" lists, newest
|
|
144
|
+
# updated first (Session.list's summaries, archived ones included; no
|
|
145
|
+
# test_run or scratch session): what .window lists before its window,
|
|
146
|
+
# and what ctx.sessions.list (the knowledge bundle's sessions source)
|
|
147
|
+
# reads. No window, no cap.
|
|
148
|
+
# @param project [:all, :none, String] :all no filter; :none the
|
|
149
|
+
# sessions in no project (Session#project_root nil); a root, the
|
|
150
|
+
# sessions of that project (a worktree's session has its repository's)
|
|
151
|
+
# @param changed_since [Time, nil] only the files written after it
|
|
152
|
+
# (Session.list's changed_since:, before any is parsed)
|
|
153
|
+
# @return [Array<Session>]
|
|
154
|
+
def summaries(project: :all, changed_since: nil, state_dir: Session.default_state_dir)
|
|
155
|
+
keep(listing(state_dir: state_dir, changed_since: changed_since), project, {})
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# Every saved session's id, from the folder's file names (no file read):
|
|
159
|
+
# what an index of sessions keeps rows for.
|
|
160
|
+
# @return [Array<String>]
|
|
161
|
+
def present_ids(state_dir: Session.default_state_dir)
|
|
162
|
+
Dir.glob(File.join(state_dir, "*#{SessionPaths::FILE_EXT}"))
|
|
163
|
+
.map { |path| File.basename(path, SessionPaths::FILE_EXT) }.select { |id| SessionPaths.valid_id?(id) }
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
def listing(state_dir:, changed_since: nil)
|
|
167
|
+
Session.list(state_dir: state_dir, include_archived: true, sort: "updated_at", order: "desc",
|
|
168
|
+
changed_since: changed_since)
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
# +listed+ without test_run and scratch sessions, of +project+ (as
|
|
172
|
+
# .summaries takes it); +cache+ is Session#project_root's.
|
|
173
|
+
def keep(listed, project, cache)
|
|
174
|
+
kept = listed.reject { |s| s.test_run || s.scratch }
|
|
175
|
+
case project
|
|
176
|
+
when :all then kept
|
|
177
|
+
when :none then kept.select { |s| s.project_root(cache: cache).nil? }
|
|
178
|
+
else kept.select { |s| s.project_root(cache: cache) == project.to_s }
|
|
179
|
+
end
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
# The window and each kept session's counts.
|
|
183
|
+
# @return [Listing]
|
|
184
|
+
def read(project: nil, now: Time.now)
|
|
185
|
+
found = window(project: project, now: now)
|
|
186
|
+
since = Time.iso8601(found.since)
|
|
187
|
+
hosts = configured_hosts
|
|
188
|
+
unreadable = found.unreadable
|
|
189
|
+
sessions = found.summaries.map do |summary|
|
|
190
|
+
counts, unread = session_counts(summary, since: since, hosts: hosts)
|
|
191
|
+
unreadable += unread
|
|
192
|
+
counts
|
|
193
|
+
end
|
|
194
|
+
Listing.new(project: found.project, picked_by: found.picked_by, projects: found.projects,
|
|
195
|
+
sessions: sessions.freeze, since: found.since, sessions_capped: found.capped, unreadable: unreadable)
|
|
196
|
+
end
|
|
197
|
+
|
|
198
|
+
# One session's counts over the window (what .read does per kept
|
|
199
|
+
# session; not the runtime's API).
|
|
200
|
+
# @param summary [Session] a Session.list summary
|
|
201
|
+
# @param since [Time]
|
|
202
|
+
# @param hosts [Hash] config.yml's hosts (a model ref's host prefix)
|
|
203
|
+
# @return [Array(SessionCounts, Integer)] the counts, and how many of its
|
|
204
|
+
# files didn't read
|
|
205
|
+
def session_counts(summary, since:, hosts: configured_hosts)
|
|
206
|
+
dir = Session.session_dir(summary.id)
|
|
207
|
+
analytics = AnalyticsFile.read(dir)
|
|
208
|
+
unreadable = analytics.nil? && File.exist?(AnalyticsFile.path(dir)) ? 1 : 0
|
|
209
|
+
analytics ||= {}
|
|
210
|
+
records = hashes(analytics["turn_records"]).select { |t| (at = time(t["started_at"])) && at >= since }
|
|
211
|
+
turn_ids = records.to_h { |t| [t["id"], true] }.except(nil)
|
|
212
|
+
tools = hashes(analytics["tool_records"]).select { |r| turn_ids.key?(r["turn_id"]) }
|
|
213
|
+
by_turn = tools.group_by { |r| r["turn_id"] }
|
|
214
|
+
lines, steers, unread_messages = message_counts(summary.id, since)
|
|
215
|
+
cards, unread_cards = card_counts(dir, turn_ids, since)
|
|
216
|
+
counts = SessionCounts.new(
|
|
217
|
+
id: summary.id, created_at: summary.created_at, updated_at: summary.updated_at, model_name: summary.model_name,
|
|
218
|
+
delegate: summary.delegate?, chain_link: !summary.continues.to_s.empty?,
|
|
219
|
+
turns: records.map { |t| turn_counts(t, by_turn.fetch(t["id"], []), hosts) }.freeze,
|
|
220
|
+
tool_calls_by_tool: tally(tools), tool_errors_by_tool: tally(tools.select { |r| r["status"] == "error" }),
|
|
221
|
+
blocked: tools.count { |r| r["status"] == "blocked" }, auto_allowed: tools.count { |r| r["guardrail"] },
|
|
222
|
+
mid_turn_lines: lines, steers_by_source: steers, **cards,
|
|
223
|
+
context_window: analytics["context"].is_a?(Hash) ? number(analytics["context"]["window_tokens"]) : nil,
|
|
224
|
+
side_cost: side_cost(analytics["side"]), schedule_id: schedule_id(summary.first_turn_client_id)
|
|
225
|
+
)
|
|
226
|
+
[counts, unreadable + unread_messages + unread_cards]
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
# config.yml's hosts, by name ({} with none).
|
|
230
|
+
def configured_hosts
|
|
231
|
+
hosts = ConfigFile.section("hosts")
|
|
232
|
+
hosts.is_a?(Hash) ? hosts : {}
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
# The project +project+'s folder is in, else the newest kept session a
|
|
236
|
+
# person started's, else the newest kept session with a root's.
|
|
237
|
+
# @return [Array(String, String)] the root and how it was picked, or [nil, nil]
|
|
238
|
+
def pick_root(project, kept, roots, cache)
|
|
239
|
+
unless project.to_s.empty?
|
|
240
|
+
root = ProjectScope.root_for(File.expand_path(project.to_s), cache: cache)
|
|
241
|
+
return [root, "folder"] if root
|
|
242
|
+
end
|
|
243
|
+
with_root = kept.select { |s| roots[s.id] }
|
|
244
|
+
newest = with_root.find { |s| person_started?(s) } || with_root.first
|
|
245
|
+
newest ? [roots[newest.id], "newest"] : [nil, nil]
|
|
246
|
+
end
|
|
247
|
+
|
|
248
|
+
# A session a person started: not a delegate, and its first prompt's
|
|
249
|
+
# sender is none (an older file, an idle start, a continue, chi send)
|
|
250
|
+
# or the owner's (a web tab, a TUI: ClientId.owner?).
|
|
251
|
+
def person_started?(summary)
|
|
252
|
+
return false if summary.delegate?
|
|
253
|
+
|
|
254
|
+
sender = summary.first_turn_client_id
|
|
255
|
+
sender.nil? || ClientId.owner?(sender)
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
def project_of(root, count) = Project.new(name: File.basename(root), path: Paths.tilde(root), session_count: count)
|
|
259
|
+
|
|
260
|
+
def turn_counts(record, tools, hosts)
|
|
261
|
+
status = record["status"].to_s
|
|
262
|
+
cancel = cancel_of(status, record["cancellation_reason"].to_s)
|
|
263
|
+
bundle = record["cancelled_by"].to_s
|
|
264
|
+
bundle = "hook" if bundle.empty?
|
|
265
|
+
TurnCounts.new(
|
|
266
|
+
id: record["id"], started_at: record["started_at"], status: status, cancel: cancel,
|
|
267
|
+
cancel_bundle: cancel == "hook" ? bundle : nil,
|
|
268
|
+
automatic: record["automatic"] == true, model: model_of(record, hosts), cost: cost_of(record),
|
|
269
|
+
tool_calls: tools.size, tool_errors: tools.count { |r| r["status"] == "error" },
|
|
270
|
+
tool_calls_by_tool: tally(tools), tool_errors_by_tool: tally(tools.select { |r| r["status"] == "error" }),
|
|
271
|
+
failure_kind: status == "failed" ? failure_kind(record["failure"]) : nil,
|
|
272
|
+
context_used_tokens: number(record["context_used_tokens"])
|
|
273
|
+
)
|
|
274
|
+
end
|
|
275
|
+
|
|
276
|
+
# CANCELS' word for a turn, nil for one that wasn't canceled.
|
|
277
|
+
def cancel_of(status, reason)
|
|
278
|
+
return "interrupted" if reason == INTERRUPTED || status == INTERRUPTED
|
|
279
|
+
return nil unless status == "canceled"
|
|
280
|
+
return "you" if YOU_REASONS.include?(reason)
|
|
281
|
+
|
|
282
|
+
reason == "hook" ? "hook" : "other"
|
|
283
|
+
end
|
|
284
|
+
|
|
285
|
+
# The record's model, else its model_ref without a configured host's
|
|
286
|
+
# prefix ("main:org/model:Q4" is "org/model:Q4"; "org/model:Q4" stays).
|
|
287
|
+
def model_of(record, hosts)
|
|
288
|
+
model = record["model"]
|
|
289
|
+
return model if model.is_a?(String) && !model.empty?
|
|
290
|
+
|
|
291
|
+
ref = record["model_ref"]
|
|
292
|
+
return nil unless ref.is_a?(String) && !ref.empty?
|
|
293
|
+
|
|
294
|
+
ModelRef.split(ref, hosts: hosts).last
|
|
295
|
+
end
|
|
296
|
+
|
|
297
|
+
# Reported plus estimated: a generation has one or the other
|
|
298
|
+
# (SessionMetrics::Cost). String keys, as analytics.json reads.
|
|
299
|
+
def cost_of(record) = number(record["cost"]).to_f + number(record["cost_estimate"]).to_f
|
|
300
|
+
|
|
301
|
+
# @param failure [Hash, nil] a turn record's failure
|
|
302
|
+
# @return [String] a FAILURE_KINDS word
|
|
303
|
+
def failure_kind(failure)
|
|
304
|
+
failure = {} unless failure.is_a?(Hash)
|
|
305
|
+
line = %w[summary message error_class].map { |key| failure[key] }.find { |v| v.is_a?(String) && !v.strip.empty? }
|
|
306
|
+
return "none" unless line
|
|
307
|
+
|
|
308
|
+
line = line.scrub
|
|
309
|
+
FAILURE_RULES.find { |_, pattern| pattern.match?(line) }&.first || "other"
|
|
310
|
+
end
|
|
311
|
+
|
|
312
|
+
# The owner's mid-turn lines (input Speaker.of reads as :owner, no turn
|
|
313
|
+
# start) and the plugins' steers by source, whose time is in the window.
|
|
314
|
+
# Only role, kind, source, author, turn_start and the time are looked at.
|
|
315
|
+
# @return [Array(Integer, Hash, Integer)] lines, steers, unreadable files
|
|
316
|
+
def message_counts(id, since)
|
|
317
|
+
data = JSON.parse(File.read(Session.session_file(id)))
|
|
318
|
+
messages = data.is_a?(Hash) && data["messages"].is_a?(Array) ? data["messages"] : []
|
|
319
|
+
lines = 0
|
|
320
|
+
steers = Hash.new(0)
|
|
321
|
+
messages.each do |message|
|
|
322
|
+
next unless message.is_a?(Hash)
|
|
323
|
+
next unless (at = time(message[MessageTime::KEY.to_s])) && at >= since
|
|
324
|
+
|
|
325
|
+
case message["kind"]
|
|
326
|
+
when Steer::INPUT_KIND
|
|
327
|
+
lines += 1 if Speaker.of(message) == :owner && !message["turn_start"]
|
|
328
|
+
when Steer::KIND then steers[message["source"].to_s] += 1
|
|
329
|
+
end
|
|
330
|
+
end
|
|
331
|
+
[lines, steers.to_h.freeze, 0]
|
|
332
|
+
rescue JSON::ParserError, SystemCallError
|
|
333
|
+
[0, {}.freeze, 1]
|
|
334
|
+
end
|
|
335
|
+
|
|
336
|
+
# cards.json's approvals by rule and hook notices by bundle in the
|
|
337
|
+
# window, and whether it is at either cap. Read raw (symbol keys, String
|
|
338
|
+
# types), as `chi guardrails replay` reads it; a version other than
|
|
339
|
+
# CardStore's (2) doesn't read.
|
|
340
|
+
# @return [Array(Hash, Integer)] the SessionCounts members, unreadable files
|
|
341
|
+
def card_counts(dir, turn_ids, since)
|
|
342
|
+
path = File.join(dir, Bridge::CardStore::FILE)
|
|
343
|
+
return [empty_cards, 0] unless File.exist?(path)
|
|
344
|
+
|
|
345
|
+
data = JSON.parse(File.read(path), symbolize_names: true)
|
|
346
|
+
unless data.is_a?(Hash) && data[:version] == Bridge::CardStore::FORMAT_VERSION && data[:entries].is_a?(Array)
|
|
347
|
+
return [empty_cards, 1]
|
|
348
|
+
end
|
|
349
|
+
|
|
350
|
+
entries = data[:entries].grep(Hash)
|
|
351
|
+
in_window = entries.select { |entry| entry_in_window?(entry, turn_ids, since) }
|
|
352
|
+
notice_types = Bridge::CardStore::NOTICE_TYPES.map(&:to_s)
|
|
353
|
+
llm_types = Bridge::CardStore::LLM_CONTEXT_TYPES.map(&:to_s)
|
|
354
|
+
types = entries.map { |entry| entry[:type].to_s }
|
|
355
|
+
[{ approvals_by_rule: approvals(in_window), hook_notices_by_bundle: hook_notices(in_window),
|
|
356
|
+
cards_at_cap: types.count { |t| !notice_types.include?(t) && !llm_types.include?(t) } >= Bridge::CardStore::CAPACITY,
|
|
357
|
+
notices_at_cap: types.count { |t| notice_types.include?(t) } >= Bridge::CardStore::CAPACITY }, 0]
|
|
358
|
+
rescue JSON::ParserError, SystemCallError
|
|
359
|
+
[empty_cards, 1]
|
|
360
|
+
end
|
|
361
|
+
|
|
362
|
+
def empty_cards
|
|
363
|
+
{ approvals_by_rule: {}.freeze, hook_notices_by_bundle: {}.freeze, cards_at_cap: false, notices_at_cap: false }
|
|
364
|
+
end
|
|
365
|
+
|
|
366
|
+
# An entry of a windowed turn; a question with no turn id by when it
|
|
367
|
+
# was asked; any other entry without one is left out.
|
|
368
|
+
def entry_in_window?(entry, turn_ids, since)
|
|
369
|
+
return turn_ids.key?(entry[:turn_id]) unless entry[:turn_id].nil?
|
|
370
|
+
return false unless entry[:type] == "question" && entry[:pending_question].is_a?(Hash)
|
|
371
|
+
|
|
372
|
+
(at = time(entry[:pending_question][:created_at])) && at >= since
|
|
373
|
+
end
|
|
374
|
+
|
|
375
|
+
def approvals(entries)
|
|
376
|
+
rows = Hash.new { |hash, rule| hash[rule] = APPROVAL_COUNTS.to_h { |count| [count, 0] } }
|
|
377
|
+
entries.each do |entry|
|
|
378
|
+
next unless entry[:type] == "question" && entry[:pending_question].is_a?(Hash)
|
|
379
|
+
|
|
380
|
+
facts = Guardrails::ApprovalFacts.from_h(entry[:pending_question][:approval])
|
|
381
|
+
next unless facts
|
|
382
|
+
|
|
383
|
+
row = rows[facts.rule.to_s.empty? ? NO_RULE : facts.rule.to_s]
|
|
384
|
+
row["asked"] += 1
|
|
385
|
+
answer = entry[:answer]
|
|
386
|
+
next row["unanswered"] += 1 if entry[:cancelled] || !answer.is_a?(Hash)
|
|
387
|
+
|
|
388
|
+
index = Array(answer[:selected_indices]).first
|
|
389
|
+
label = SystemOne::ApprovalLabel.choice(index.is_a?(Integer) ? index : nil, Array(facts.scopes))
|
|
390
|
+
row[{ "allow_once" => "once", "allow_wide" => "wide" }.fetch(label, "denied")] += 1
|
|
391
|
+
row["by_parent"] += 1 if answer[:by] == "parent_agent"
|
|
392
|
+
end
|
|
393
|
+
rows.transform_values(&:freeze).freeze
|
|
394
|
+
end
|
|
395
|
+
|
|
396
|
+
# Hook notices by bundle (HookLabel.source). A label that is neither a
|
|
397
|
+
# bundle hook's nor one word (a hook's failure line) is skipped.
|
|
398
|
+
def hook_notices(entries)
|
|
399
|
+
counts = Hash.new(0)
|
|
400
|
+
entries.each do |entry|
|
|
401
|
+
next unless entry[:type] == "hook_notice"
|
|
402
|
+
|
|
403
|
+
label = entry[:hook].to_s
|
|
404
|
+
source = HookLabel.source(label)
|
|
405
|
+
next if source == label && (label.empty? || label.match?(/\s/))
|
|
406
|
+
|
|
407
|
+
counts[source] += 1
|
|
408
|
+
end
|
|
409
|
+
counts.to_h.freeze
|
|
410
|
+
end
|
|
411
|
+
|
|
412
|
+
def side_cost(side)
|
|
413
|
+
return 0.0 unless side.is_a?(Hash)
|
|
414
|
+
|
|
415
|
+
number(side["cost_sum"]).to_f + number(side["cost_estimate_sum"]).to_f
|
|
416
|
+
end
|
|
417
|
+
|
|
418
|
+
def schedule_id(sender)
|
|
419
|
+
return nil unless sender.is_a?(String) && sender.start_with?(ClientId::SCHEDULE_PREFIX)
|
|
420
|
+
|
|
421
|
+
id = sender.delete_prefix(ClientId::SCHEDULE_PREFIX)
|
|
422
|
+
id.empty? ? nil : id
|
|
423
|
+
end
|
|
424
|
+
|
|
425
|
+
def tally(records) = records.map { |r| r["tool"].to_s }.tally.freeze
|
|
426
|
+
|
|
427
|
+
def hashes(value) = value.is_a?(Array) ? value.grep(Hash) : []
|
|
428
|
+
|
|
429
|
+
def number(value) = value.is_a?(Numeric) ? value : nil
|
|
430
|
+
|
|
431
|
+
def time(value)
|
|
432
|
+
value.is_a?(String) ? Time.iso8601(value) : nil
|
|
433
|
+
rescue ArgumentError
|
|
434
|
+
nil
|
|
435
|
+
end
|
|
436
|
+
end
|
|
437
|
+
end
|
|
@@ -50,6 +50,9 @@ module Samagotchi
|
|
|
50
50
|
continue: "the bridge endpoint belongs to the old worker", corpus_dir: SIDE_CAR),
|
|
51
51
|
Store.new(file: "cards.json", owner: "Bridge::CardStore", removal: :session_files, cross_version: true,
|
|
52
52
|
continue: "cards describe turns in the previous link", corpus_dir: SIDE_CAR),
|
|
53
|
+
# The bundles' own chips (ctx.chips): read by chi web with no worker running.
|
|
54
|
+
Store.new(file: "chips.json", owner: "SessionChips", removal: :session_files, cross_version: true,
|
|
55
|
+
continue: "a continue copies nothing; the bundle sets its chips again", corpus_dir: SIDE_CAR),
|
|
53
56
|
Store.new(file: "pending_card.json", owner: "Bridge::PendingCard", removal: :session_files, cross_version: true,
|
|
54
57
|
continue: "an open card belongs to its running turn", corpus_dir: SIDE_CAR),
|
|
55
58
|
Store.new(file: "turn_drawings.jsonl", owner: "Bridge::TurnDrawings", removal: :session_files, cross_version: true,
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "config"
|
|
4
|
+
|
|
5
|
+
module Samagotchi
|
|
6
|
+
# How far back a report over the saved sessions reads: days, capped by the
|
|
7
|
+
# retention (`session.retention_days`), and how many sessions, capped by
|
|
8
|
+
# `session.max_count`. A setting that isn't a positive number caps nothing.
|
|
9
|
+
# Unlike SessionRetention's resolvers (what the sweep keeps), these only
|
|
10
|
+
# ever lower the caller's own limit. `chi toolkit report` reads its window here.
|
|
11
|
+
module SessionWindow
|
|
12
|
+
module_function
|
|
13
|
+
|
|
14
|
+
# @param requested [Integer] the days asked for
|
|
15
|
+
# @param max [Integer] the caller's own cap
|
|
16
|
+
# @return [Integer]
|
|
17
|
+
def days(requested, max: 14)
|
|
18
|
+
retention = Config.get("session.retention_days").to_i
|
|
19
|
+
cap = retention.positive? ? [retention, max].min : max
|
|
20
|
+
[requested, cap].min
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# @param max [Integer] the caller's own cap
|
|
24
|
+
# @return [Integer]
|
|
25
|
+
def max_sessions(max: 500)
|
|
26
|
+
count = Config.get("session.max_count").to_i
|
|
27
|
+
count.positive? ? [max, count].min : max
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
end
|