samagotchi 0.177.0 → 0.178.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 +44 -1
- data/docs/architecture.md +5 -4
- data/docs/cli.md +31 -6
- data/docs/guardrails.md +1 -1
- data/docs/internals/background-tasks.md +23 -2
- data/docs/internals/bridge.md +17 -6
- data/docs/internals/bundles.md +4 -3
- data/docs/internals/participants.md +8 -5
- data/docs/internals/remote-sessions.md +6 -1
- data/docs/internals/session-lifecycle.md +176 -0
- data/docs/internals/web-frontend.md +14 -6
- data/docs/internals/working-set.md +33 -6
- data/docs/plugins.md +1 -1
- data/docs/releasing.md +3 -2
- data/docs/scheduling.md +8 -1
- data/docs/sessions.md +15 -9
- data/docs/testing.md +4 -2
- data/lib/samagotchi/bridge/card_store.rb +2 -19
- data/lib/samagotchi/bridge.rb +38 -6
- data/lib/samagotchi/bundle_command/check.rb +1 -1
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/compat.rb +0 -7
- data/lib/samagotchi/engine/events.rb +43 -0
- data/lib/samagotchi/engine/session.rb +7 -0
- data/lib/samagotchi/engine.rb +9 -3
- data/lib/samagotchi/event_fanout.rb +56 -0
- data/lib/samagotchi/guardrails/approvals.rb +0 -4
- data/lib/samagotchi/memory_bundle/shipped_update.rb +1 -1
- data/lib/samagotchi/note_delivery.rb +9 -4
- data/lib/samagotchi/plugin/sessions.rb +2 -1
- data/lib/samagotchi/revise_anchor.rb +2 -0
- data/lib/samagotchi/schedules.rb +12 -5
- data/lib/samagotchi/session_access/contract.rb +4 -0
- data/lib/samagotchi/session_access/local.rb +16 -4
- data/lib/samagotchi/session_access/remote.rb +42 -9
- data/lib/samagotchi/session_archive_command.rb +38 -10
- data/lib/samagotchi/session_chain/delete.rb +98 -25
- data/lib/samagotchi/session_chain/delete_preview.rb +2 -2
- data/lib/samagotchi/session_delete_command.rb +33 -10
- data/lib/samagotchi/session_inbox.rb +29 -0
- data/lib/samagotchi/session_inbox_delivery.rb +13 -5
- data/lib/samagotchi/session_lifecycle/allowed.rb +69 -0
- data/lib/samagotchi/session_lifecycle/canonical.rb +49 -0
- data/lib/samagotchi/session_lifecycle/reading.rb +65 -0
- data/lib/samagotchi/session_lifecycle.rb +59 -0
- data/lib/samagotchi/session_manager/delivery.rb +29 -6
- data/lib/samagotchi/session_manager/lifecycle.rb +33 -39
- data/lib/samagotchi/session_manager/removal.rb +117 -25
- data/lib/samagotchi/session_manager/running_tasks.rb +334 -0
- data/lib/samagotchi/session_manager/spawn.rb +2 -2
- data/lib/samagotchi/sessions_command.rb +1 -1
- data/lib/samagotchi/system_prompt.rb +22 -2
- data/lib/samagotchi/task_files.rb +37 -4
- data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +7 -1
- data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
- data/lib/samagotchi/terminal_ui/local_link.rb +11 -3
- data/lib/samagotchi/tool_names.rb +1 -1
- data/lib/samagotchi/tools/memory.rb +29 -0
- data/lib/samagotchi/tools/task_runtime.rb +25 -6
- data/lib/samagotchi/turn_anchors.rb +5 -0
- data/lib/samagotchi/verify_anchor.rb +2 -0
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +5 -1
- data/lib/samagotchi/web/participant_show.rb +3 -4
- data/lib/samagotchi/web/participant_view.rb +4 -6
- data/lib/samagotchi/web/public/data.js +19 -3
- data/lib/samagotchi/web/public/delete_sheet.js +67 -11
- data/lib/samagotchi/web/public/running_tasks.js +73 -0
- data/lib/samagotchi/web/public/session_actions.js +57 -8
- data/lib/samagotchi/web/public/stop_sheet.js +3 -2
- data/lib/samagotchi/web/public/working_set.js +3 -28
- data/lib/samagotchi/web/public/working_set_view.js +5 -2
- data/lib/samagotchi/web/public/ws_item_sig.js +51 -0
- data/lib/samagotchi/web/public/ws_peek.js +23 -13
- data/lib/samagotchi/web/public/ws_reader.js +22 -12
- data/lib/samagotchi/web/public/ws_sections.js +1 -0
- data/lib/samagotchi/web/public/ws_timeline.js +9 -6
- data/lib/samagotchi/web/session_control.rb +66 -16
- data/lib/samagotchi/web/session_summary.rb +7 -0
- data/lib/samagotchi/web/working_set_routes.rb +29 -8
- data/lib/samagotchi/worker_boot.rb +9 -6
- data/lib/samagotchi/worker_link.rb +9 -1
- data/lib/samagotchi/worker_presence.rb +4 -0
- data/lib/samagotchi/working_set.rb +26 -0
- data/lib/samagotchi/working_set_command.rb +10 -7
- data/lib/samagotchi/working_set_steer.rb +3 -10
- metadata +9 -1
|
@@ -103,7 +103,7 @@ module Samagotchi
|
|
|
103
103
|
# prompt_parts: the same as sizes, one PromptPart per memory, file and
|
|
104
104
|
# plugin section, the tools part first (#prompt_parts).
|
|
105
105
|
Built = Data.define(:prompt, :memory_index, :notes, :files, :sections, :stable_length, :surface, :memory_names, :parts,
|
|
106
|
-
:prompt_parts)
|
|
106
|
+
:prompt_parts, :prompt_memories)
|
|
107
107
|
|
|
108
108
|
# One part of the prompt: its kind (KINDS), what it was made from (the
|
|
109
109
|
# memory names of identity and preloads, the files of agents and
|
|
@@ -137,6 +137,7 @@ module Samagotchi
|
|
|
137
137
|
@memory_index = built.memory_index
|
|
138
138
|
@last = built
|
|
139
139
|
@last_prompt_memory_names = built.memory_names
|
|
140
|
+
@last_prompt_memories = built.prompt_memories
|
|
140
141
|
built.prompt
|
|
141
142
|
end
|
|
142
143
|
|
|
@@ -167,6 +168,11 @@ module Samagotchi
|
|
|
167
168
|
# @return [Array<String>]
|
|
168
169
|
def prompt_memory_names = @last_prompt_memory_names || []
|
|
169
170
|
|
|
171
|
+
# The identity and preloaded memories in the last built prompt, with the
|
|
172
|
+
# scope each memory answered from; retained across reset! like the names.
|
|
173
|
+
# @return [Array<Array(String, String, nil)>]
|
|
174
|
+
def prompt_memories = @last_prompt_memories || []
|
|
175
|
+
|
|
170
176
|
# The files whose text the prompt #build returned last holds, as
|
|
171
177
|
# absolute paths in prompt order: the AGENTS.md chain, then the
|
|
172
178
|
# appended files (append_system_prompt:, --append-system-prompt). [] before a
|
|
@@ -240,10 +246,24 @@ module Samagotchi
|
|
|
240
246
|
prompt_parts = Degrade.call(:prompt, "prompt_parts_failed", fallback: []) do
|
|
241
247
|
prompt_parts_for(@section_parts, chat: chat, surface: surface)
|
|
242
248
|
end
|
|
249
|
+
prompt_memories = prompt_memories_for(@section_parts)
|
|
243
250
|
Built.new(prompt: prompt, memory_index: @measured_index, notes: @section_notes || [],
|
|
244
251
|
files: @section_files.freeze, sections: @section_plugins.freeze, stable_length: @measured_stable_length,
|
|
245
252
|
surface: surface, memory_names: [@section_identity_memory_name, *@section_activated_memory_names].compact.uniq.freeze,
|
|
246
|
-
parts: @section_parts.freeze, prompt_parts: prompt_parts.freeze)
|
|
253
|
+
parts: @section_parts.freeze, prompt_parts: prompt_parts.freeze, prompt_memories: prompt_memories)
|
|
254
|
+
end
|
|
255
|
+
|
|
256
|
+
def prompt_memories_for(sections)
|
|
257
|
+
sections.flat_map do |section|
|
|
258
|
+
case section.kind
|
|
259
|
+
when :identity
|
|
260
|
+
section.ref ? [[section.ref, "system"]] : []
|
|
261
|
+
when :preloads
|
|
262
|
+
Array(section_items(section)).map { |_, name, _, scope| [name, scope] }
|
|
263
|
+
else
|
|
264
|
+
[]
|
|
265
|
+
end
|
|
266
|
+
end.map(&:freeze).uniq.freeze
|
|
247
267
|
end
|
|
248
268
|
|
|
249
269
|
# ── The parts' sizes ───────────────────────────────────────────────────────
|
|
@@ -20,26 +20,59 @@ module Samagotchi
|
|
|
20
20
|
# A task id as task_create makes them: no path parts.
|
|
21
21
|
TASK_ID = /\A[A-Za-z0-9_-]+\z/
|
|
22
22
|
|
|
23
|
+
# The thread-local root #with_root sets.
|
|
24
|
+
ROOT_KEY = :samagotchi_task_root
|
|
25
|
+
|
|
23
26
|
module_function
|
|
24
27
|
|
|
28
|
+
# Runs the block with this thread's task paths under +root+ (a
|
|
29
|
+
# session's working directory) instead of the cwd: chi web and the CLI
|
|
30
|
+
# stop a session's tasks this way (SessionManager::RunningTasks.stop!).
|
|
31
|
+
# Per thread: a thread the block starts doesn't inherit it (only
|
|
32
|
+
# create_task starts waiters, and nothing calls it under a root).
|
|
33
|
+
# Without a root every path is the relative one it always was.
|
|
34
|
+
# A nil or empty +root+ is no root (the cwd's relative paths).
|
|
35
|
+
def with_root(root)
|
|
36
|
+
before = Thread.current[ROOT_KEY]
|
|
37
|
+
Thread.current[ROOT_KEY] = root.nil? || root.to_s.empty? ? nil : root.to_s
|
|
38
|
+
yield
|
|
39
|
+
ensure
|
|
40
|
+
Thread.current[ROOT_KEY] = before
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# This thread's #with_root, or nil (the cwd).
|
|
44
|
+
def root = Thread.current[ROOT_KEY]
|
|
45
|
+
|
|
46
|
+
# +path+ under this thread's root when it is relative and a root is
|
|
47
|
+
# set; else +path+ unchanged.
|
|
48
|
+
def rooted(path)
|
|
49
|
+
base = root
|
|
50
|
+
return path if base.nil? || path.nil? || path.to_s.empty? || File.absolute_path?(path.to_s)
|
|
51
|
+
|
|
52
|
+
File.join(base, path.to_s)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# tmp/tasks, under this thread's root when one is set.
|
|
56
|
+
def tasks_dir = rooted(TASKS_DIR)
|
|
57
|
+
|
|
25
58
|
def metadata_path(task_id)
|
|
26
59
|
File.join(task_dir_for(task_id), METADATA_FILENAME)
|
|
27
60
|
end
|
|
28
61
|
|
|
29
62
|
def task_dir_for(task_id)
|
|
30
|
-
File.join(
|
|
63
|
+
File.join(tasks_dir, task_id.to_s)
|
|
31
64
|
end
|
|
32
65
|
|
|
33
66
|
# The command of the task +task_id+ under +root+ (a session's working
|
|
34
|
-
# directory) as its record has it, for a UI row's title; nil for no
|
|
67
|
+
# directory; by default this thread's root, else the cwd) as its record has it, for a UI row's title; nil for no
|
|
35
68
|
# such task or an unreadable record. Reads the record only (no
|
|
36
69
|
# refresh), so it is cheap and never fails.
|
|
37
70
|
# @return [String, nil]
|
|
38
|
-
def command_of(task_id, root:
|
|
71
|
+
def command_of(task_id, root: nil)
|
|
39
72
|
id = task_id.to_s.strip
|
|
40
73
|
return nil unless id.match?(TASK_ID)
|
|
41
74
|
|
|
42
|
-
path = File.join(root || Dir.pwd, TASKS_DIR, id, METADATA_FILENAME)
|
|
75
|
+
path = File.join(root || self.root || Dir.pwd, TASKS_DIR, id, METADATA_FILENAME)
|
|
43
76
|
return nil unless File.file?(path)
|
|
44
77
|
|
|
45
78
|
command = Tools::TaskRecord.from_file(JSON.parse(File.read(path)))&.command
|
|
@@ -104,6 +104,11 @@ module Samagotchi
|
|
|
104
104
|
rescue SystemCallError, IOError => e
|
|
105
105
|
detach("#{ExitLines.exit_failed_line(e.message, via: via, session_id: id)} Not deleted.")
|
|
106
106
|
rescue SessionManager::DeleteRefused, SessionManager::OwnedByTUI, ArgumentError => e
|
|
107
|
+
if e.is_a?(SessionManager::DeleteRefused) && e.reason == :tasks_running
|
|
108
|
+
return detach("Detached; the worker is stopping, but session #{id} was not deleted (#{e.message}; " \
|
|
109
|
+
"#{SessionManager::RunningTasks.hint(via, "delete", id)}).")
|
|
110
|
+
end
|
|
111
|
+
|
|
107
112
|
detach("Detached; the worker is stopping, but session #{id} was not deleted (#{e.message}): " \
|
|
108
113
|
"#{via.command("sessions delete #{id}")}")
|
|
109
114
|
end
|
|
@@ -147,7 +152,8 @@ module Samagotchi
|
|
|
147
152
|
rescue SystemCallError, IOError => e
|
|
148
153
|
detach("#{ExitLines.exit_failed_line(e.message, via: via, session_id: id)} Not archived.")
|
|
149
154
|
rescue SessionManager::ArchiveRefused, SessionManager::OwnedByTUI, ArgumentError => e
|
|
150
|
-
|
|
155
|
+
hint = "; #{SessionManager::RunningTasks.hint(via, "archive", id)}" if e.is_a?(SessionManager::ArchiveRefused) && e.reason == :tasks_running
|
|
156
|
+
detach("Detached; session #{id} was not archived (#{e.message}#{hint}). Re-attach with: #{via.attach(id)}")
|
|
151
157
|
end
|
|
152
158
|
end
|
|
153
159
|
end
|
|
@@ -119,7 +119,7 @@ module Samagotchi
|
|
|
119
119
|
default_input: false, wait_at_eof: false, as_parent: false, scratch: false,
|
|
120
120
|
clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }, now: -> { MessageTime.now },
|
|
121
121
|
delete_session: LocalLink::DELETE,
|
|
122
|
-
archive_session:
|
|
122
|
+
archive_session: LocalLink::ARCHIVE,
|
|
123
123
|
installed_version: -> { InstalledVersions.new.newest },
|
|
124
124
|
state_dir: Session.default_state_dir,
|
|
125
125
|
children_counts: ->(id) { ChildrenStatus.counts(id, state_dir: state_dir) }, link: nil)
|
|
@@ -28,9 +28,17 @@ module Samagotchi
|
|
|
28
28
|
DELETE_WAIT = 10
|
|
29
29
|
# /exit --delete on this machine (LocalLink's and AttachedLoop's
|
|
30
30
|
# default): a user's delete, so a chain's newest link is undone and the
|
|
31
|
-
# previous one comes back (SessionManager.delete_session's keywords)
|
|
31
|
+
# previous one comes back (SessionManager.delete_session's keywords),
|
|
32
|
+
# and background tasks still running refuse it (RunningTasks REFUSE:
|
|
33
|
+
# the line names chi sessions delete --stop-tasks).
|
|
32
34
|
DELETE = lambda do |id|
|
|
33
|
-
SessionManager.delete_session(id, stop: true, wait: DELETE_WAIT, revive_previous: true, refuse_continuing: true
|
|
35
|
+
SessionManager.delete_session(id, stop: true, wait: DELETE_WAIT, revive_previous: true, refuse_continuing: true,
|
|
36
|
+
running_tasks: SessionManager::RunningTasks::Policy::REFUSE)
|
|
37
|
+
end
|
|
38
|
+
# /archive on this machine (LocalLink's and AttachedLoop's default):
|
|
39
|
+
# refused while background tasks it or a delegate started still run.
|
|
40
|
+
ARCHIVE = lambda do |id|
|
|
41
|
+
SessionManager.archive_session(id, wait: DELETE_WAIT, running_tasks: SessionManager::RunningTasks::Policy::REFUSE)
|
|
34
42
|
end
|
|
35
43
|
|
|
36
44
|
attr_reader :client
|
|
@@ -44,7 +52,7 @@ module Samagotchi
|
|
|
44
52
|
# @param children_counts [#call] session id -> ChildrenStatus::Counts
|
|
45
53
|
def initialize(client:, state_dir: Session.default_state_dir,
|
|
46
54
|
delete_session: DELETE,
|
|
47
|
-
archive_session:
|
|
55
|
+
archive_session: ARCHIVE,
|
|
48
56
|
installed_version: -> { InstalledVersions.new.newest },
|
|
49
57
|
children_counts: ->(id) { ChildrenStatus.counts(id, state_dir: state_dir) })
|
|
50
58
|
@client = client
|
|
@@ -4,7 +4,7 @@ module Samagotchi
|
|
|
4
4
|
# chi's built-in tools' names, and the fixed texts some of them write into
|
|
5
5
|
# their results, apart from the tool classes: the code that only names a
|
|
6
6
|
# tool or matches a result to draw a row (ToolActivity, ToolView, FileRef,
|
|
7
|
-
#
|
|
7
|
+
# Objectives::Backing) reads them here and loads no tool class (Tools::Execute
|
|
8
8
|
# alone brings TaskRuntime, Shell, Leftovers, the process group…).
|
|
9
9
|
#
|
|
10
10
|
# Each tool class keeps its own constants, read from here
|
|
@@ -76,6 +76,35 @@ module Samagotchi
|
|
|
76
76
|
nil
|
|
77
77
|
end
|
|
78
78
|
|
|
79
|
+
# Whether +target+ names a memory held in the prompt. A bare target
|
|
80
|
+
# matches by name; an explicitly scoped target also matches an
|
|
81
|
+
# unscoped prompt entry by name for older prompt data.
|
|
82
|
+
def self.prompt_memory?(target, memories)
|
|
83
|
+
target_scope, target_name = prompt_memory_target(target)
|
|
84
|
+
return false if target_name.empty?
|
|
85
|
+
|
|
86
|
+
Array(memories).any? do |memory|
|
|
87
|
+
prompt_name, prompt_scope = memory.is_a?(Array) ? memory : [memory, nil]
|
|
88
|
+
prompt_name = prompt_memory_name(prompt_name)
|
|
89
|
+
prompt_scope = normalize_scope(prompt_scope)
|
|
90
|
+
prompt_name == target_name && (!target_scope || !prompt_scope || target_scope == prompt_scope)
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def self.prompt_memory_target(value)
|
|
95
|
+
name = value.to_s.strip
|
|
96
|
+
scope, name = name.split("/", 2) if name.include?("/")
|
|
97
|
+
[normalize_scope(scope), scope && VALID_SCOPES.include?(scope) ? name : value.to_s.strip]
|
|
98
|
+
end
|
|
99
|
+
private_class_method :prompt_memory_target
|
|
100
|
+
|
|
101
|
+
def self.prompt_memory_name(value)
|
|
102
|
+
name = value.to_s.strip
|
|
103
|
+
scope, suffix = name.split("/", 2) if name.include?("/")
|
|
104
|
+
scope && VALID_SCOPES.include?(scope) ? suffix : name
|
|
105
|
+
end
|
|
106
|
+
private_class_method :prompt_memory_name
|
|
107
|
+
|
|
79
108
|
def self.overlay_prefix(key) = "#{SEPARATOR}Model-specific guidance (#{key}):\n"
|
|
80
109
|
|
|
81
110
|
def self.append_overlay(body, overlay_text, key) = "#{body}#{overlay_prefix(key)}#{overlay_text}"
|
|
@@ -39,6 +39,7 @@ module Samagotchi
|
|
|
39
39
|
# signals, since two held? probes at once read each other as holders.
|
|
40
40
|
LEFTOVER_GRACE_SEC = Leftovers::GRACE_SEC
|
|
41
41
|
LEFTOVER_STOP_GRACE_SEC = 1.0
|
|
42
|
+
SETTLE_ON_EXIT_SECONDS = LEFTOVER_GRACE_SEC + LEFTOVER_STOP_GRACE_SEC + ProcessGroup::KILL_WAIT_SEC + 0.5
|
|
42
43
|
REFRESH_STOP_GRACE_SEC = 0.5
|
|
43
44
|
REFRESH_KILL_WAIT_SEC = 0.5
|
|
44
45
|
HELD_RECHECK_SEC = 0.05
|
|
@@ -148,7 +149,7 @@ module Samagotchi
|
|
|
148
149
|
forget_waiter(task_id, Thread.current)
|
|
149
150
|
end
|
|
150
151
|
thread.name = EXIT_STATUS_THREAD
|
|
151
|
-
remember_waiter(task_id, thread, started&.pid)
|
|
152
|
+
remember_waiter(task_id, thread, started&.pid, waiter)
|
|
152
153
|
thread
|
|
153
154
|
end
|
|
154
155
|
|
|
@@ -167,8 +168,8 @@ module Samagotchi
|
|
|
167
168
|
end
|
|
168
169
|
end
|
|
169
170
|
|
|
170
|
-
def remember_waiter(task_id, thread, pid)
|
|
171
|
-
@waiters_lock.synchronize { @waiters[task_id] = [thread, pid] if thread.alive? }
|
|
171
|
+
def remember_waiter(task_id, thread, pid, detach)
|
|
172
|
+
@waiters_lock.synchronize { @waiters[task_id] = [thread, pid, detach] if thread.alive? }
|
|
172
173
|
end
|
|
173
174
|
|
|
174
175
|
def forget_waiter(task_id, thread)
|
|
@@ -212,7 +213,9 @@ module Samagotchi
|
|
|
212
213
|
def log_paths(record)
|
|
213
214
|
return [] unless record
|
|
214
215
|
|
|
215
|
-
|
|
216
|
+
# A relative log (create_task's output_path) is read under the
|
|
217
|
+
# thread's root (TaskFiles.with_root); the record keeps it as is.
|
|
218
|
+
[record.output_path, record.stderr_path].filter_map { |log| TaskFiles.rooted(log.to_s) unless log.to_s.empty? }
|
|
216
219
|
end
|
|
217
220
|
|
|
218
221
|
# The one line task_get, task_wait (and the finish note) and task_list
|
|
@@ -233,6 +236,22 @@ module Samagotchi
|
|
|
233
236
|
# record_exit_status's threads' name.
|
|
234
237
|
EXIT_STATUS_THREAD = "task_exit_status"
|
|
235
238
|
|
|
239
|
+
# Join this process's already-reaped tasks, sharing one timeout. A
|
|
240
|
+
# shell that exits after the snapshot is not included.
|
|
241
|
+
# @return [Array<Thread>] the selected waiters still alive at the deadline
|
|
242
|
+
def settle_pending!(timeout:)
|
|
243
|
+
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
|
|
244
|
+
threads = @waiters_lock.synchronize do
|
|
245
|
+
@waiters.values.filter_map do |thread, _pid, detach|
|
|
246
|
+
thread if thread != Thread.current && thread.alive? && (!detach.alive? || thread[SETTLING])
|
|
247
|
+
end
|
|
248
|
+
end
|
|
249
|
+
threads.each { |thread| thread.join([deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max) }
|
|
250
|
+
alive = threads.select(&:alive?)
|
|
251
|
+
Log.warn(:turn, "task_leftovers_unsettled", count: alive.size) unless alive.empty?
|
|
252
|
+
alive
|
|
253
|
+
end
|
|
254
|
+
|
|
236
255
|
# Joins every live EXIT_STATUS_THREAD, for up to +timeout+ s in all: a
|
|
237
256
|
# spec calls it (with_task_dir) after stopping its tasks and before it
|
|
238
257
|
# removes their folder, which a recorder may still write into. chi
|
|
@@ -306,7 +325,7 @@ module Samagotchi
|
|
|
306
325
|
|
|
307
326
|
def list_records
|
|
308
327
|
ensure_tasks_dir
|
|
309
|
-
task_dirs = Dir.glob(File.join(TaskFiles
|
|
328
|
+
task_dirs = Dir.glob(File.join(TaskFiles.tasks_dir, "*"))
|
|
310
329
|
.select { |path| File.directory?(path) }
|
|
311
330
|
|
|
312
331
|
task_dirs.map do |task_dir|
|
|
@@ -504,7 +523,7 @@ module Samagotchi
|
|
|
504
523
|
def record_json(record) = JSON.pretty_generate(record.to_file) + "\n"
|
|
505
524
|
|
|
506
525
|
def ensure_tasks_dir
|
|
507
|
-
FileUtils.mkdir_p(TaskFiles
|
|
526
|
+
FileUtils.mkdir_p(TaskFiles.tasks_dir)
|
|
508
527
|
end
|
|
509
528
|
|
|
510
529
|
def generate_task_id
|
|
@@ -40,6 +40,11 @@ module Samagotchi
|
|
|
40
40
|
# A :prompt_restored event's fields.
|
|
41
41
|
def to_h = { verify: verify&.to_h, revises: revises&.to_h }.compact
|
|
42
42
|
|
|
43
|
+
# What a participant sees of each anchor.
|
|
44
|
+
def participant_view
|
|
45
|
+
self.class.members.to_h { |member| [member.to_s, public_send(member)&.participant_view] }.compact
|
|
46
|
+
end
|
|
47
|
+
|
|
43
48
|
# Engine#run_turn's keywords.
|
|
44
49
|
def kwargs = { verify:, revises: }.compact
|
|
45
50
|
end
|
data/lib/samagotchi/version.rb
CHANGED
data/lib/samagotchi/web/app.rb
CHANGED
|
@@ -1109,8 +1109,12 @@ module Samagotchi
|
|
|
1109
1109
|
# DELETE …/chain, and the plain delete's revive and undo (D2/D5): chi
|
|
1110
1110
|
# --remote sessions delete --chain asks for this first.
|
|
1111
1111
|
CHAIN_DELETE_FEATURE = "chain_delete"
|
|
1112
|
+
# Delete and archive refuse on running background tasks (409
|
|
1113
|
+
# tasks_running) and take stop_tasks: chi --remote sessions
|
|
1114
|
+
# delete|archive --stop-tasks asks for this first.
|
|
1115
|
+
STOP_TASKS_FEATURE = "stop_tasks"
|
|
1112
1116
|
INFO_FEATURES = ["dir", "newest_workers", SessionAccessRoutes::FEATURE, SessionAccessRoutes::ATTACH_FEATURE,
|
|
1113
|
-
BOUND_FEATURE, CHAIN_DELETE_FEATURE].freeze
|
|
1117
|
+
BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE].freeze
|
|
1114
1118
|
|
|
1115
1119
|
# The models a new session can start on, spelled as chi spells them
|
|
1116
1120
|
# elsewhere: bare for the default host (what default.model holds), and
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
require "json"
|
|
4
4
|
require_relative "participant_view"
|
|
5
5
|
require_relative "viewer"
|
|
6
|
+
require_relative "session_summary"
|
|
6
7
|
require_relative "../bridge/turn_accumulator"
|
|
7
8
|
require_relative "../worker_link"
|
|
8
9
|
require_relative "../verify_anchor"
|
|
@@ -89,8 +90,7 @@ module Samagotchi
|
|
|
89
90
|
# delivery line, the stale-worker badge), its verdicts (filtered) and whether Verify fresh can run.
|
|
90
91
|
def participant_session_json(reads, features, viewer)
|
|
91
92
|
session = reads.session
|
|
92
|
-
status =
|
|
93
|
-
status = Session::STATUS_IDLE if status == Session::STATUS_RUNNING && reads.turn_snapshot && reads.current_turn.nil?
|
|
93
|
+
status = SessionSummary.shown_status(session, reads.state, reads.turn_snapshot, owner: session_owner(session.id))
|
|
94
94
|
dir = Session.session_dir(reads.id, state_dir: default_state_dir)
|
|
95
95
|
{ id: session.id, title: participant_title(session), status: status,
|
|
96
96
|
bridge_up: !reads.turn_snapshot.nil?, worker_features: Array(features),
|
|
@@ -197,8 +197,7 @@ module Samagotchi
|
|
|
197
197
|
shown = messages_for_display(raw, parts: true, cwd: session.working_directory, markdown: false)
|
|
198
198
|
messages = ParticipantView.messages(shown, viewer)
|
|
199
199
|
answer = participant_answer(messages, turn_id.empty? ? nil : turn_id)
|
|
200
|
-
status =
|
|
201
|
-
status = Session::STATUS_IDLE if status == Session::STATUS_RUNNING && reads.turn_snapshot && reads.current_turn.nil?
|
|
200
|
+
status = SessionSummary.shown_status(session, reads.state, reads.turn_snapshot, owner: session_owner(session.id))
|
|
202
201
|
json_response(200, {
|
|
203
202
|
tail: true,
|
|
204
203
|
session: { id: id, status: status, used_memory_names: [], prompt_notes: [], prompt_parts: [] },
|
|
@@ -4,8 +4,7 @@ require_relative "../output_formatter"
|
|
|
4
4
|
require_relative "../model_markup"
|
|
5
5
|
require_relative "../steer"
|
|
6
6
|
require_relative "../turn_origin"
|
|
7
|
-
require_relative "../
|
|
8
|
-
require_relative "../verify_anchor"
|
|
7
|
+
require_relative "../turn_anchors"
|
|
9
8
|
require_relative "../redact"
|
|
10
9
|
require_relative "../file_ref"
|
|
11
10
|
require_relative "../image_store"
|
|
@@ -138,8 +137,8 @@ module Samagotchi
|
|
|
138
137
|
# their image refs (#image_refs), the Revise draft's turn id and the
|
|
139
138
|
# origin's ids the page matches it by (restore.js restoreAction). nil
|
|
140
139
|
# for anyone else's, the owner's or an automatic turn (decided by the
|
|
141
|
-
# origin's author, which chi web stamped).
|
|
142
|
-
#
|
|
140
|
+
# origin's author, which chi web stamped). Only a parsed Verify claim is
|
|
141
|
+
# carried beyond those fields.
|
|
143
142
|
def prompt_restored(event, viewer)
|
|
144
143
|
origin = field(event, :origin)
|
|
145
144
|
return nil unless origin.is_a?(Hash)
|
|
@@ -150,8 +149,7 @@ module Samagotchi
|
|
|
150
149
|
out = { "type" => "prompt_restored", **seq(event), "prompt" => field(event, :prompt).to_s }
|
|
151
150
|
images = image_refs(field(event, :images), author, viewer)
|
|
152
151
|
out["images"] = images if images
|
|
153
|
-
|
|
154
|
-
out["revises"] = { "turn_id" => revises.turn_id } if revises
|
|
152
|
+
out.merge!(TurnAnchors.new(verify: field(event, :verify), revises: field(event, :revises)).participant_view)
|
|
155
153
|
out["origin"] = { "client_id" => field(origin, :client_id).to_s, "enqueued_id" => field(origin, :enqueued_id).to_s,
|
|
156
154
|
"author" => author.to_s }
|
|
157
155
|
out
|
|
@@ -270,8 +270,12 @@ export function restartSession(id, opts = {}) {
|
|
|
270
270
|
|
|
271
271
|
// Hides the session (and its delegates) from the lists, kept for good; the
|
|
272
272
|
// server stops a live idle worker first and answers 409 while a turn runs.
|
|
273
|
+
// stopTasks: stop the background tasks it and its delegates started first
|
|
274
|
+
// (without it, a session whose tasks still run is refused: 409 tasks_running).
|
|
273
275
|
export function archiveSession(id, opts = {}) {
|
|
274
|
-
|
|
276
|
+
const { stopTasks, ...apiOpts } = opts;
|
|
277
|
+
const body = JSON.stringify(stopTasks ? { stop_tasks: true } : {});
|
|
278
|
+
return api(`/api/sessions/${encodeURIComponent(id)}/archive`, { method: "POST", body, ...apiOpts });
|
|
275
279
|
}
|
|
276
280
|
|
|
277
281
|
// Back to the lists, delegates too.
|
|
@@ -279,16 +283,28 @@ export function unarchiveSession(id, opts = {}) {
|
|
|
279
283
|
return api(`/api/sessions/${encodeURIComponent(id)}/unarchive`, { method: "POST", body: JSON.stringify({}), ...opts });
|
|
280
284
|
}
|
|
281
285
|
|
|
286
|
+
// A delete's query after force=true: the plan digest the user confirmed
|
|
287
|
+
// (expect), and stop_tasks (stop the background tasks the deleted sessions
|
|
288
|
+
// started first; without it, 409 tasks_running while one runs).
|
|
289
|
+
function deleteQuery({ expect, stopTasks }) {
|
|
290
|
+
const plan = expect == null ? "" : `&expect=${encodeURIComponent(expect)}`;
|
|
291
|
+
return `${plan}${stopTasks ? "&stop_tasks=true" : ""}`;
|
|
292
|
+
}
|
|
293
|
+
|
|
282
294
|
// Deletes the session for good; force=true has the server stop a live
|
|
283
295
|
// worker first (the page's confirm says so; without it, 409 worker_running).
|
|
284
296
|
export function deleteSession(id, opts = {}) {
|
|
285
|
-
|
|
297
|
+
const { expect, stopTasks, ...apiOpts } = opts;
|
|
298
|
+
return api(`/api/sessions/${encodeURIComponent(id)}?force=true${deleteQuery({ expect, stopTasks })}`,
|
|
299
|
+
{ method: "DELETE", ...apiOpts });
|
|
286
300
|
}
|
|
287
301
|
|
|
288
302
|
// Deletes every link of the session's chain with their delegates (running
|
|
289
303
|
// ones are left running); force: the links' workers are stopped first.
|
|
290
304
|
export function deleteChain(id, opts = {}) {
|
|
291
|
-
|
|
305
|
+
const { expect, stopTasks, ...apiOpts } = opts;
|
|
306
|
+
return api(`/api/sessions/${encodeURIComponent(id)}/chain?force=true${deleteQuery({ expect, stopTasks })}`,
|
|
307
|
+
{ method: "DELETE", ...apiOpts });
|
|
292
308
|
}
|
|
293
309
|
|
|
294
310
|
// What deleting a chained session would do, for the delete sheet
|
|
@@ -7,8 +7,9 @@
|
|
|
7
7
|
// The sheet's words come from GET /api/sessions/:id/delete_plan, the plan
|
|
8
8
|
// and refusals the server's delete itself runs (SessionChain::Delete::
|
|
9
9
|
// Preview), fetched as the sheet opens and only for a chained session: a
|
|
10
|
-
// session in no chain keeps today's confirm (session_actions.js).
|
|
11
|
-
//
|
|
10
|
+
// session in no chain keeps today's confirm (session_actions.js). The
|
|
11
|
+
// confirmed digest is checked by the delete; a changed plan is re-read and
|
|
12
|
+
// shown for a fresh confirmation.
|
|
12
13
|
//
|
|
13
14
|
// Where it is drawn (a host): the ⋯ More panel turns into it, with ‹ More to
|
|
14
15
|
// go back (more_sheet.js' subview); a card's ✕ opens it at the card, on
|
|
@@ -19,6 +20,7 @@
|
|
|
19
20
|
import { html, nothing, render } from "./vendor/lit-html.js";
|
|
20
21
|
import { createChipPopover } from "./chip_popover.js";
|
|
21
22
|
import { cardName, clip, normalize } from "./format.js";
|
|
23
|
+
import { tasksCount, tasksLine } from "./running_tasks.js";
|
|
22
24
|
|
|
23
25
|
const short = (id) => String(id ?? "").slice(0, 8);
|
|
24
26
|
const count = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
@@ -111,6 +113,19 @@ export function deleteChoices(session, plan) {
|
|
|
111
113
|
};
|
|
112
114
|
}
|
|
113
115
|
|
|
116
|
+
function unchainedChoices(session, plan) {
|
|
117
|
+
const id = session?.id ?? plan?.session_id;
|
|
118
|
+
const name = sessionName(session);
|
|
119
|
+
return {
|
|
120
|
+
title: `Delete ${short(id)}${name ? ` — "${name}"` : ""}?`,
|
|
121
|
+
sub: "This session is no longer in a chain. This can't be undone.",
|
|
122
|
+
banner: null,
|
|
123
|
+
choices: [{ act: "this", label: "Delete this session", lines: ["Its turns and session data will be permanently deleted."],
|
|
124
|
+
primary: true }],
|
|
125
|
+
foot: "This can't be undone.",
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
114
129
|
function choiceTemplate(choice) {
|
|
115
130
|
const cls = `ds-choice${choice.primary ? " primary" : ""}`;
|
|
116
131
|
if (choice.disabled) {
|
|
@@ -132,11 +147,12 @@ function headTemplate(back) {
|
|
|
132
147
|
|
|
133
148
|
// The choices (a lit-html template). +busy+: a delete under way (every
|
|
134
149
|
// button off); +back+: drawn in the More panel.
|
|
135
|
-
export function deleteSheetTemplate(model, { back = false, busy = false } = {}) {
|
|
150
|
+
export function deleteSheetTemplate(model, { back = false, busy = false, notice = null } = {}) {
|
|
136
151
|
const allOff = model.choices.every((c) => c.disabled);
|
|
137
152
|
return html`<div class=${`delete-sheet${busy ? " busy" : ""}`}>${headTemplate(back)}
|
|
138
153
|
<div class="ds-title">${model.title}</div>
|
|
139
154
|
<div class="ds-sub">${model.sub}</div>
|
|
155
|
+
${notice ? html`<div class="ds-banner">${notice}</div>` : nothing}
|
|
140
156
|
${model.banner ? html`<div class="ds-banner">${model.banner}</div>` : nothing}
|
|
141
157
|
<div class="ds-choices" ?inert=${busy}>${model.choices.map(choiceTemplate)}</div>
|
|
142
158
|
<div class="ds-foot">${allOff ? html`<span></span>` : html`<span class="ds-note">${busy ? "Deleting…" : model.foot}</span>`}
|
|
@@ -151,10 +167,22 @@ export function loadingTemplate({ back = false } = {}) {
|
|
|
151
167
|
|
|
152
168
|
// A refused delete, in the sheet: a moved delegate that can't go back
|
|
153
169
|
// (delegate_unmovable: "Stop its worker, then delete" only when the page
|
|
154
|
-
// can stop it, not a one-turn run's),
|
|
155
|
-
//
|
|
170
|
+
// can stop it, not a one-turn run's), background tasks the delete takes
|
|
171
|
+
// still running (tasks_running: "Stop them and delete"), or any other
|
|
172
|
+
// refusal's own words.
|
|
173
|
+
// @param refusal {reason, message, ids, stoppable, tasks, sessionId}
|
|
156
174
|
// @param previousId the link the delegate would go back to
|
|
157
175
|
export function refusalModel(refusal, previousId = null) {
|
|
176
|
+
if (refusal?.reason === "tasks_running") {
|
|
177
|
+
const n = tasksCount(refusal.tasks);
|
|
178
|
+
return {
|
|
179
|
+
title: "Background tasks still running",
|
|
180
|
+
text: `${count(n, "background task")} this delete takes ${n === 1 ? "is" : "are"} still running: ` +
|
|
181
|
+
`${tasksLine(refusal.tasks, refusal.sessionId)}. Nothing was deleted.`,
|
|
182
|
+
stop: { label: n === 1 ? "Stop it and delete" : "Stop them and delete",
|
|
183
|
+
line: `${n === 1 ? "It is" : "They are"} stopped (TERM, then KILL after 3 s), then the session goes.` },
|
|
184
|
+
};
|
|
185
|
+
}
|
|
158
186
|
if (refusal?.reason === "delegate_unmovable") {
|
|
159
187
|
const id = (refusal.ids || [])[0];
|
|
160
188
|
const back = previousId ? short(previousId) : "the previous link";
|
|
@@ -224,6 +252,7 @@ export function listAfterDelete(list, result) {
|
|
|
224
252
|
export function runDeleteFlow({ id, session, host, api, done, plain, failed }) {
|
|
225
253
|
let plan = null;
|
|
226
254
|
let model = null;
|
|
255
|
+
let notice = null;
|
|
227
256
|
let refusal = null;
|
|
228
257
|
let busy = false;
|
|
229
258
|
const back = !!host.back;
|
|
@@ -233,7 +262,7 @@ export function runDeleteFlow({ id, session, host, api, done, plain, failed }) {
|
|
|
233
262
|
const live = () => (host.live ? host.live() : true);
|
|
234
263
|
const show = (tpl) => { if (live()) host.show(tpl); };
|
|
235
264
|
|
|
236
|
-
const showChoices = () => show(deleteSheetTemplate(model, { back, busy }));
|
|
265
|
+
const showChoices = () => show(deleteSheetTemplate(model, { back, busy, notice }));
|
|
237
266
|
const showRefusal = () => show(refusalTemplate(refusalModel(refusal, plan?.link?.previous_id), { back }));
|
|
238
267
|
|
|
239
268
|
show(loadingTemplate({ back }));
|
|
@@ -247,22 +276,48 @@ export function runDeleteFlow({ id, session, host, api, done, plain, failed }) {
|
|
|
247
276
|
|
|
248
277
|
// The refusal as the delete's 409 says it; whether the page can stop a
|
|
249
278
|
// moved delegate's worker is its +stoppable+, as the delete saw it.
|
|
250
|
-
|
|
251
|
-
|
|
279
|
+
// A tasks_running refusal keeps its tasks and the choice it refused
|
|
280
|
+
// (+which+), so "Stop them and delete" sends that choice again.
|
|
281
|
+
function refused(error, which) {
|
|
282
|
+
refusal = { reason: error.code, message: error.message, ids: error.body?.ids || [], stoppable: error.body?.stoppable === true,
|
|
283
|
+
tasks: error.body?.tasks || null, sessionId: id, which };
|
|
252
284
|
busy = false;
|
|
253
285
|
showRefusal();
|
|
254
286
|
}
|
|
255
287
|
|
|
256
|
-
|
|
288
|
+
// +stopTasks+: the same choice and digest, the tasks stopped first.
|
|
289
|
+
async function run(which, { stopTasks = false } = {}) {
|
|
257
290
|
if (busy || !live()) return;
|
|
258
291
|
busy = true;
|
|
259
292
|
showChoices();
|
|
260
293
|
try {
|
|
261
|
-
const
|
|
294
|
+
const digest = which === "chain" ? plan?.chain?.digest : plan?.link?.digest;
|
|
295
|
+
const opts = stopTasks ? { expect: digest, stopTasks: true } : { expect: digest };
|
|
296
|
+
const result = which === "chain" ? await api.deleteChain(id, opts) : await api.deleteSession(id, opts);
|
|
262
297
|
if (live()) host.close();
|
|
263
298
|
done(which, result, plan);
|
|
264
299
|
} catch (error) {
|
|
265
|
-
|
|
300
|
+
if (error.code === "plan_changed") {
|
|
301
|
+
await refreshPlan();
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
refused(error, which);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function refreshPlan() {
|
|
309
|
+
show(loadingTemplate({ back }));
|
|
310
|
+
try {
|
|
311
|
+
const read = await api.deletePlan(id);
|
|
312
|
+
if (!live()) return;
|
|
313
|
+
plan = read;
|
|
314
|
+
model = read?.chained ? deleteChoices(session, plan) : unchainedChoices(session, plan);
|
|
315
|
+
notice = "What this deletes changed; check again";
|
|
316
|
+
busy = false;
|
|
317
|
+
showChoices();
|
|
318
|
+
} catch (error) {
|
|
319
|
+
busy = false;
|
|
320
|
+
if (live()) { host.close(); failed(error); }
|
|
266
321
|
}
|
|
267
322
|
}
|
|
268
323
|
|
|
@@ -294,6 +349,7 @@ export function runDeleteFlow({ id, session, host, api, done, plain, failed }) {
|
|
|
294
349
|
if (!live()) return;
|
|
295
350
|
if (name === "cancel") host.close();
|
|
296
351
|
else if (name === "this" || name === "chain") run(name);
|
|
352
|
+
else if (name === "stop" && refusal?.reason === "tasks_running") run(refusal.which, { stopTasks: true });
|
|
297
353
|
else if (name === "stop") stopThenDelete();
|
|
298
354
|
},
|
|
299
355
|
};
|