samagotchi 0.176.0 → 0.177.1
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 +47 -1
- data/docs/architecture.md +5 -4
- data/docs/cli.md +12 -5
- data/docs/internals/bundles.md +4 -3
- data/docs/internals/participants.md +10 -6
- data/docs/internals/prompt-caching.md +3 -0
- data/docs/internals/session-lifecycle.md +167 -0
- data/docs/internals/web-frontend.md +25 -8
- data/docs/internals/working-set.md +78 -6
- data/docs/plugins.md +1 -1
- data/docs/releasing.md +3 -2
- data/docs/sessions.md +8 -5
- data/docs/testing.md +4 -2
- data/lib/samagotchi/bridge.rb +3 -3
- data/lib/samagotchi/bundle_command/check.rb +1 -1
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/compat.rb +1 -1
- data/lib/samagotchi/engine/models.rb +11 -0
- data/lib/samagotchi/engine/session.rb +16 -0
- data/lib/samagotchi/engine.rb +1 -0
- data/lib/samagotchi/engine_snapshots.rb +3 -0
- 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/prompt_part.rb +66 -0
- data/lib/samagotchi/revise_anchor.rb +2 -0
- data/lib/samagotchi/schedules.rb +3 -1
- data/lib/samagotchi/session.rb +10 -1
- data/lib/samagotchi/session_chain/delete.rb +28 -5
- data/lib/samagotchi/session_chain/delete_preview.rb +2 -2
- data/lib/samagotchi/session_inbox.rb +29 -0
- data/lib/samagotchi/session_inbox_delivery.rb +13 -5
- data/lib/samagotchi/session_lifecycle/allowed.rb +66 -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 +22 -14
- data/lib/samagotchi/session_manager/removal.rb +16 -8
- data/lib/samagotchi/session_manager/spawn.rb +2 -2
- data/lib/samagotchi/sessions_command.rb +1 -1
- data/lib/samagotchi/system_prompt.rb +211 -12
- data/lib/samagotchi/tool_names.rb +1 -1
- data/lib/samagotchi/tools/memory.rb +29 -0
- 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/participant_show.rb +4 -5
- data/lib/samagotchi/web/participant_view.rb +4 -6
- data/lib/samagotchi/web/public/app.js +3 -0
- data/lib/samagotchi/web/public/ctx_tokens.js +33 -0
- data/lib/samagotchi/web/public/data.js +6 -2
- data/lib/samagotchi/web/public/delete_sheet.js +42 -5
- data/lib/samagotchi/web/public/index.html +43 -9
- data/lib/samagotchi/web/public/session_fields.js +10 -4
- data/lib/samagotchi/web/public/session_prefs.js +5 -2
- data/lib/samagotchi/web/public/session_state.js +14 -1
- data/lib/samagotchi/web/public/session_store.js +1 -1
- data/lib/samagotchi/web/public/session_view.js +1 -1
- data/lib/samagotchi/web/public/stream_handlers.js +7 -3
- data/lib/samagotchi/web/public/tokens.css +2 -2
- data/lib/samagotchi/web/public/working_set.js +51 -7
- data/lib/samagotchi/web/public/working_set_view.js +188 -58
- data/lib/samagotchi/web/public/ws_sections.js +252 -0
- data/lib/samagotchi/web/session_control.rb +4 -3
- data/lib/samagotchi/web/session_show.rb +13 -2
- data/lib/samagotchi/web/session_summary.rb +7 -0
- data/lib/samagotchi/worker/command_queue.rb +5 -1
- data/lib/samagotchi/worker/startup.rb +1 -1
- data/lib/samagotchi/worker.rb +1 -0
- data/lib/samagotchi/worker_boot.rb +9 -6
- data/lib/samagotchi/worker_presence.rb +4 -0
- data/lib/samagotchi/working_set.rb +32 -4
- data/lib/samagotchi/working_set_command.rb +3 -2
- data/lib/samagotchi/working_set_steer.rb +14 -3
- metadata +9 -1
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
// The working set's head view (docs/internals/working-set.md, The head
|
|
2
|
+
// view): the popover's list as what is in chi's head, in three sections.
|
|
3
|
+
// start From the start: the system prompt's parts (the session's
|
|
4
|
+
// prompt_parts), in prompt order, the tools part first. A memory
|
|
5
|
+
// part (identity, a model note, a preload) IS a memory row: merged
|
|
6
|
+
// with the session set's rows of that name and scope (`same`: a
|
|
7
|
+
// scope either side lacks matches by name alone, an older worker's
|
|
8
|
+
// or a set item not read yet), else a row of its own (identity:
|
|
9
|
+
// the set never lists it; a system x beside a project x read: key
|
|
10
|
+
// `x@system`, no actions). Other parts are `part` rows: a label, a
|
|
11
|
+
// sub, their tokens, no actions.
|
|
12
|
+
// read Read in this session: today's files / memories / urls sections
|
|
13
|
+
// (working_set.js bodySections), minus the memories shown in start.
|
|
14
|
+
// talk Conversation: one row (drawn at section level, no header, no
|
|
15
|
+
// fold), the rest of the context: the context's
|
|
16
|
+
// tokens minus the parts' and the held items'. Mixed units (parts and
|
|
17
|
+
// items are chars/4, the context's the server's count or the
|
|
18
|
+
// calibrated estimate): the "~" says so.
|
|
19
|
+
// No parts (an old session or worker, a participant): none of this, the
|
|
20
|
+
// list is today's (headSections returns null).
|
|
21
|
+
//
|
|
22
|
+
// No DOM: `node --test` covers the rules; working_set_view.js draws them.
|
|
23
|
+
// A module of its own: static JS is cached at unversioned URLs, and a new
|
|
24
|
+
// export on an old module would blank the page.
|
|
25
|
+
import { bodySections, itemKey, tokensText } from "./working_set.js";
|
|
26
|
+
|
|
27
|
+
// The sections folded by hand, per session (session_prefs.js): a JSON list
|
|
28
|
+
// of section keys. None: all open.
|
|
29
|
+
export const WS_SECTION_FOLD = "chi_ws_sections_folded";
|
|
30
|
+
|
|
31
|
+
export const MEMORY_PARTS = Object.freeze(["identity", "notes", "preloads"]);
|
|
32
|
+
|
|
33
|
+
// What a memory part's row says it is.
|
|
34
|
+
const MEMORY_WORDS = { identity: "identity memory", notes: "model note", preloads: "preloaded" };
|
|
35
|
+
// A part row's sub text, by kind (the tools part's is its label, "31 declared").
|
|
36
|
+
const PART_SUBS = { agents: "project instructions", appended: "appended", plugins: "plugin section" };
|
|
37
|
+
|
|
38
|
+
// A memory's name as memory_read takes it: a leading project/ or system/
|
|
39
|
+
// scope is not part of it (an older page's preloaded key).
|
|
40
|
+
export function memoryName(name) {
|
|
41
|
+
const m = /^(project|system)\/(.+)$/.exec(String(name || "").trim());
|
|
42
|
+
return m ? m[2] : String(name || "").trim();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const struck = (item) => item.state === "forgotten" || item.state === "dropped";
|
|
46
|
+
const held = (item) => !item.muted && !item.added && !struck(item);
|
|
47
|
+
const sum = (list, of) => list.reduce((n, x) => n + (Number.isFinite(of(x)) ? of(x) : 0), 0);
|
|
48
|
+
|
|
49
|
+
// Whether two scopes can be the same memory's: equal, or either unknown
|
|
50
|
+
// (an older worker's part or item, a set item the server hasn't read).
|
|
51
|
+
const sameScope = (a, b) => !a || !b || a === b;
|
|
52
|
+
|
|
53
|
+
// Whether +item+ (a set item) is the memory +part+ names: its name, and its
|
|
54
|
+
// scope when both know theirs.
|
|
55
|
+
// The server-side twin is Tools::MemoryRead.prompt_memory? in tools/memory.rb.
|
|
56
|
+
export const same = (part, item) => item.kind === "memory" && memoryName(item.key) === memoryName(part.ref) && sameScope(part.scope, item.scope);
|
|
57
|
+
|
|
58
|
+
// A part's row: never an item the set or a steer line knows.
|
|
59
|
+
function partRow(part, key) {
|
|
60
|
+
const tools = part.kind === "tools";
|
|
61
|
+
return {
|
|
62
|
+
kind: "part", key, partKind: part.kind, label: tools ? "tools" : String(part.label || part.kind),
|
|
63
|
+
sub: tools ? String(part.label || "") : PART_SUBS[part.kind] || "", partTokens: Number.isFinite(part.tokens) ? part.tokens : 0,
|
|
64
|
+
ops: [], at: null, count: 0, state: "live",
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// A memory part's row: the set's rows of that name merged (its read one
|
|
69
|
+
// first: its tokens, its key for steering), or one of its own under +key+
|
|
70
|
+
// (+scoped+: the name is another scope's row's too, so its words say its
|
|
71
|
+
// scope).
|
|
72
|
+
function memoryRow(part, name, matches, key, scoped) {
|
|
73
|
+
const main = matches.find((m) => m.ops.includes("read")) || matches[0];
|
|
74
|
+
const base = main ? { ...main } : { kind: "memory", key, label: name, ops: [], at: null, count: 0, state: "live" };
|
|
75
|
+
const ops = [...new Set(matches.flatMap((m) => m.ops))];
|
|
76
|
+
const at = matches.map((m) => m.at).find(Boolean) || base.at || null;
|
|
77
|
+
return {
|
|
78
|
+
...base, ops, at, label: name, preloaded: true, partKind: part.kind, partScope: part.scope || null,
|
|
79
|
+
partTokens: Number.isFinite(part.tokens) ? part.tokens : 0, mergedKeys: matches.map(itemKey), ...(scoped ? { scopeWord: part.scope } : {}),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// A start memory row's read still sent (read, not forgotten or dropped):
|
|
84
|
+
// what "held twice", its "+X" and the conversation's arithmetic count.
|
|
85
|
+
const readHeld = (row) => row.kind === "memory" && !!row.partKind && row.ops.includes("read") && !struck(row);
|
|
86
|
+
|
|
87
|
+
// Whether a start memory row is in the prompt and its read is held too.
|
|
88
|
+
export const heldTwice = (row) => readHeld(row);
|
|
89
|
+
|
|
90
|
+
// A start memory row's words: what it is in the prompt (a read again is
|
|
91
|
+
// its "held twice" tag, or the turn lens's note).
|
|
92
|
+
export const memoryPartWords = (row) => [MEMORY_WORDS[row.partKind] || "in the prompt", row.scopeWord || ""].filter(Boolean).join(" · ");
|
|
93
|
+
|
|
94
|
+
// The keys of the set's items a start memory row stands for: never new to
|
|
95
|
+
// the head in a turn lens (the prompt had them from the start).
|
|
96
|
+
export function promptKeys(sections) {
|
|
97
|
+
return new Set((sections?.find((s) => s.key === "start")?.rows || []).flatMap((r) => r.mergedKeys || []));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// A start row's tokens: the part's, and "+X" for a memory's read (its item
|
|
101
|
+
// tokens: a preloaded row carries none of its own, so the two never
|
|
102
|
+
// double-count). "~0.6k +0.4k".
|
|
103
|
+
export function startTokensText(row) {
|
|
104
|
+
const own = tokensText(row.partTokens);
|
|
105
|
+
if (!readHeld(row) || !Number.isFinite(row.tokens)) return own;
|
|
106
|
+
return `${own} +${tokensText(row.tokens).replace(/^~/, "")}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// The held-twice note under a start memory row in a turn lens whose items
|
|
110
|
+
// read it: "read again in this turn: already in the prompt, held twice (+X)".
|
|
111
|
+
export function heldTwiceNote(row, turnItem) {
|
|
112
|
+
if (!readHeld(row) || !turnItem?.ops?.includes("read")) return "";
|
|
113
|
+
const extra = Number.isFinite(row.tokens) ? ` (+${tokensText(row.tokens).replace(/^~/, "")})` : "";
|
|
114
|
+
return `read again in this turn: already in the prompt, held twice${extra}`;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// The head view's sections for +set+ ({items, muted}: the session's set,
|
|
118
|
+
// overlaid), or null without parts (today's list). +parts+: the session's
|
|
119
|
+
// prompt_parts; +ctxTokens+: the context's tokens now (null: unknown);
|
|
120
|
+
// +turns+: how many turns the session has (the conversation row's).
|
|
121
|
+
// @return [{key, title, meta, tokens, rows?, inner?}] start, read, talk?
|
|
122
|
+
export function headSections(set, budget, { parts = null, ctxTokens = null, turns = 0, inTurn = false } = {}) {
|
|
123
|
+
if (!Array.isArray(parts) || !parts.length) return null;
|
|
124
|
+
const { rows, used, partNames } = startRows(set, parts);
|
|
125
|
+
const partsTokens = sum(rows, (r) => r.partTokens);
|
|
126
|
+
// A preloaded memory never read is the prompt's, never "read in this
|
|
127
|
+
// session": one no part names (a ref-less preloads / notes part, whose
|
|
128
|
+
// items' sizes didn't line up; a preload that failed to load) stays out.
|
|
129
|
+
const rest = {
|
|
130
|
+
items: normalized(set.items, used, partNames).filter((item) => !used.has(item) && !(item.preloaded && !item.ops.includes("read"))),
|
|
131
|
+
muted: set.muted,
|
|
132
|
+
};
|
|
133
|
+
const readItems = rest.items;
|
|
134
|
+
const out = readItems.filter(struck).length;
|
|
135
|
+
// The read section's tokens: its held items'; the start rows' reads count
|
|
136
|
+
// into the conversation's arithmetic, not into either section.
|
|
137
|
+
const readTokens = sum(readItems.filter(held), (i) => i.tokens);
|
|
138
|
+
const heldTokens = readTokens + sum(rows.filter(readHeld), (r) => r.tokens);
|
|
139
|
+
const sections = [
|
|
140
|
+
{ key: "start", title: "From the start", meta: inTurn ? "in every turn" : `${rows.length} part${rows.length === 1 ? "" : "s"} · in every turn`, tokens: partsTokens, rows },
|
|
141
|
+
{
|
|
142
|
+
key: "read", title: "Read in this session", meta: [`${readItems.filter(held).length} held`, out ? `${out} out` : ""].filter(Boolean).join(" · "),
|
|
143
|
+
tokens: readTokens, inner: bodySections(rest, budget),
|
|
144
|
+
},
|
|
145
|
+
];
|
|
146
|
+
const talk = Number.isFinite(ctxTokens) ? ctxTokens - partsTokens - heldTokens : NaN;
|
|
147
|
+
if (talk > 0) {
|
|
148
|
+
const row = { kind: "talk", key: "conversation", label: "conversation", sub: `${turns} turn${turns === 1 ? "" : "s"}`, partTokens: talk, ops: [], at: null, count: 0, state: "live" };
|
|
149
|
+
sections.push({ key: "talk", title: "Conversation", meta: "", tokens: talk, rows: [row] });
|
|
150
|
+
}
|
|
151
|
+
return sections;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// The session set's items as the head view sees them (+parts+: the
|
|
155
|
+
// session's prompt_parts; none: the items as they are): an item another
|
|
156
|
+
// scope's part names (a project x read beside a system x preload) is a
|
|
157
|
+
// plain read, not the prompt's (preloaded: false). The Read section and a
|
|
158
|
+
// turn lens's counts (turnLens) both read this list.
|
|
159
|
+
export function headItems(set, parts) {
|
|
160
|
+
if (!Array.isArray(parts) || !parts.length) return set.items;
|
|
161
|
+
const { used, partNames } = startRows(set, parts);
|
|
162
|
+
return normalized(set.items, used, partNames);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// +items+ with each one no start row shows, named by a memory part, made
|
|
166
|
+
// a plain read (a copy; the rest unchanged).
|
|
167
|
+
function normalized(items, used, partNames) {
|
|
168
|
+
return items.map((item) => (!used.has(item) && item.preloaded && item.kind === "memory" && partNames.has(memoryName(item.key)) ? { ...item, preloaded: false } : item));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// The start section's rows for +parts+, the set's items they show (+used+,
|
|
172
|
+
// by identity) and the memory names the parts claim (+partNames+).
|
|
173
|
+
function startRows(set, parts) {
|
|
174
|
+
// The set's items a start row shows, by identity: a key can be two
|
|
175
|
+
// memories' (a project x read, a system x in the prompt).
|
|
176
|
+
const used = new Set();
|
|
177
|
+
const memories = set.items.filter((item) => item.kind === "memory");
|
|
178
|
+
const rows = [];
|
|
179
|
+
const keys = new Set();
|
|
180
|
+
const seenMemory = new Map();
|
|
181
|
+
// Names a part claims: a set item of that name no part matched (another
|
|
182
|
+
// scope's) reads as read, not as the prompt's.
|
|
183
|
+
const partNames = new Set();
|
|
184
|
+
for (const part of parts) {
|
|
185
|
+
if (!part || !part.kind) continue;
|
|
186
|
+
if (MEMORY_PARTS.includes(part.kind) && part.ref) {
|
|
187
|
+
const name = memoryName(part.ref);
|
|
188
|
+
partNames.add(name);
|
|
189
|
+
const again = (seenMemory.get(name) || []).find((r) => sameScope(r.partScope, part.scope));
|
|
190
|
+
// A memory in two parts (a note also preloaded): one row, both sizes.
|
|
191
|
+
if (again) {
|
|
192
|
+
again.partTokens += Number.isFinite(part.tokens) ? part.tokens : 0;
|
|
193
|
+
if (!again.partScope && part.scope) again.partScope = part.scope;
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
const matches = memories.filter((m) => !used.has(m) && same(part, m));
|
|
197
|
+
matches.forEach((m) => used.add(m));
|
|
198
|
+
// Its own row's key: the name, or name@scope when another row or
|
|
199
|
+
// item holds that name (never two rows of one key).
|
|
200
|
+
const taken = keys.has(`memory:${name}`) || memories.some((m) => memoryName(m.key) === name && !matches.includes(m));
|
|
201
|
+
const own = !matches.length && taken ? `${name}@${part.scope || part.kind}` : name;
|
|
202
|
+
const row = memoryRow(part, name, matches, own, taken && !!part.scope);
|
|
203
|
+
seenMemory.set(name, [...(seenMemory.get(name) || []), row]);
|
|
204
|
+
keys.add(itemKey(row));
|
|
205
|
+
rows.push(row);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
let key = `${part.kind}:${part.ref ?? part.label ?? ""}`;
|
|
209
|
+
for (let n = 2; keys.has(`part:${key}`); n += 1) key = `${part.kind}:${part.ref ?? part.label ?? ""}#${n}`;
|
|
210
|
+
keys.add(`part:${key}`);
|
|
211
|
+
rows.push(partRow(part, key));
|
|
212
|
+
}
|
|
213
|
+
return { rows, used, partNames };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// +touched+ (a turn lens: the turn's items by key) with each start memory
|
|
217
|
+
// row's merged keys under its own key, so a read of `system/x` lights the
|
|
218
|
+
// row of `x` (the set holds both spellings). A turn's rows come from tool
|
|
219
|
+
// titles, which carry no scope: a part-only row (no merged item, e.g.
|
|
220
|
+
// `x@system`) lights by its bare name too (a turn that read a project x,
|
|
221
|
+
// never as held twice: that row holds no read). A row with a merged item
|
|
222
|
+
// lights by its items' keys only. The map given is not changed.
|
|
223
|
+
export function lensTouched(sections, touched) {
|
|
224
|
+
if (!touched || !sections) return touched;
|
|
225
|
+
const out = new Map(touched);
|
|
226
|
+
for (const row of sections.find((s) => s.key === "start")?.rows || []) {
|
|
227
|
+
if (!row.mergedKeys || out.has(itemKey(row))) continue;
|
|
228
|
+
const keys = row.mergedKeys.length ? row.mergedKeys : [`memory:${row.label}`];
|
|
229
|
+
const hit = keys.find((k) => touched.has(k));
|
|
230
|
+
if (hit) out.set(itemKey(row), touched.get(hit));
|
|
231
|
+
}
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// The section keys folded, from the stored value (a JSON list); unreadable: none.
|
|
236
|
+
// Conversation never folds (one row): an older page's stored "talk" is ignored.
|
|
237
|
+
export function foldedSections(stored) {
|
|
238
|
+
try {
|
|
239
|
+
const list = JSON.parse(stored || "[]");
|
|
240
|
+
return new Set(Array.isArray(list) ? list.filter((k) => typeof k === "string" && k !== "talk") : []);
|
|
241
|
+
} catch (_) {
|
|
242
|
+
return new Set();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// The head line in the session lens: "in chi's head now · ~X of Y" (Y the
|
|
247
|
+
// window; no "of Y" when unknown), "" without the context's tokens.
|
|
248
|
+
export function headLine(ctxTokens, windowTokens) {
|
|
249
|
+
if (!Number.isFinite(ctxTokens)) return "";
|
|
250
|
+
const of = Number.isFinite(windowTokens) && windowTokens > 0 ? ` of ${tokensText(windowTokens).replace(/^~/, "")}` : "";
|
|
251
|
+
return `in chi's head now · ${tokensText(ctxTokens)}${of}`;
|
|
252
|
+
}
|
|
@@ -480,7 +480,7 @@ module Samagotchi
|
|
|
480
480
|
# {status: "restarted", session_id, from_version, version} (version nil:
|
|
481
481
|
# the new worker is still starting; its bridge_up follows); 409
|
|
482
482
|
# {error: "held" | "not_running" | "unsupported" | "failed", reason, detail} in words (a stopped
|
|
483
|
-
# worker: held, reason stopped, its pid); 409
|
|
483
|
+
# worker: held, reason stopped, its pid; a stop marked: held, reason stop_marked); 409
|
|
484
484
|
# owned_by_tui; 404.
|
|
485
485
|
def handle_restart(_req, id)
|
|
486
486
|
result = @manager.restart_session(id, state_dir: @state_dir, client_id: ClientId::WEB_RESTART)
|
|
@@ -524,7 +524,8 @@ module Samagotchi
|
|
|
524
524
|
# session is always refused.
|
|
525
525
|
def handle_delete(req, id)
|
|
526
526
|
result = @manager.delete_session(id, state_dir: @state_dir, stop: truthy_param?(req.GET["force"]),
|
|
527
|
-
wait: STOP_WAIT_SECONDS, revive_previous: true, refuse_continuing: true
|
|
527
|
+
wait: STOP_WAIT_SECONDS, revive_previous: true, refuse_continuing: true,
|
|
528
|
+
expect: req.GET["expect"])
|
|
528
529
|
touch_deleted(result[:id], result)
|
|
529
530
|
json_response(200, { status: "deleted", session_id: result[:id], stopped: result[:stopped],
|
|
530
531
|
unarchived: Array(result[:unarchived]), moved_back: Array(result[:moved_back]),
|
|
@@ -539,7 +540,7 @@ module Samagotchi
|
|
|
539
540
|
# their delegates (SessionManager.delete_chain). Query-only.
|
|
540
541
|
def handle_delete_chain(req, id)
|
|
541
542
|
result = @manager.delete_chain(id, state_dir: @state_dir, stop: truthy_param?(req.GET["force"]),
|
|
542
|
-
wait: STOP_WAIT_SECONDS)
|
|
543
|
+
wait: STOP_WAIT_SECONDS, expect: req.GET["expect"])
|
|
543
544
|
touch_deleted(id, result)
|
|
544
545
|
json_response(200, { status: "deleted", session_id: id, deleted: result[:deleted], left: result[:left],
|
|
545
546
|
left_running: result[:left_running], unarchived: result[:unarchived],
|
|
@@ -297,6 +297,10 @@ module Samagotchi
|
|
|
297
297
|
refs.empty? ? pending.except(key) : pending.merge(key => refs)
|
|
298
298
|
end
|
|
299
299
|
|
|
300
|
+
# The session file's prompt parts as the wire has them ([] for a file
|
|
301
|
+
# without the field).
|
|
302
|
+
def saved_prompt_parts(session) = Array(session.prompt_parts).map(&:to_h)
|
|
303
|
+
|
|
300
304
|
# The full show's session part: the file's, with what a live worker's
|
|
301
305
|
# state +snapshot+ knows first (its model, status, served model,
|
|
302
306
|
# prompt notes and chips); without one, the served model from
|
|
@@ -310,6 +314,9 @@ module Samagotchi
|
|
|
310
314
|
served_expected_by: snapshot["served_expected_by"])
|
|
311
315
|
# The model notes its prompt carries now (a /model there changes them).
|
|
312
316
|
session_json = session_json.merge(prompt_notes: snapshot["prompt_notes"]) if snapshot["prompt_notes"].is_a?(Array)
|
|
317
|
+
# And the sizes of its parts (the head view's "From the start"); an
|
|
318
|
+
# older worker's snapshot has none: the file's, [] for an older file.
|
|
319
|
+
session_json = session_json.merge(prompt_parts: snapshot["prompt_parts"].is_a?(Array) ? snapshot["prompt_parts"] : saved_prompt_parts(session))
|
|
313
320
|
# The newest context estimate the worker has (a turn in flight: the
|
|
314
321
|
# last request's), so a page opened mid-turn shows the percent at
|
|
315
322
|
# once. Owner show only: a participant's show is ParticipantView's
|
|
@@ -317,7 +324,7 @@ module Samagotchi
|
|
|
317
324
|
# nothing, so its page reads as it always did.
|
|
318
325
|
session_json = session_json.merge(context_status: snapshot["context_status"]) if snapshot.key?("context_status")
|
|
319
326
|
else
|
|
320
|
-
session_json = session_json.merge(saved_served_model(session, persisted))
|
|
327
|
+
session_json = session_json.merge(saved_served_model(session, persisted), prompt_parts: saved_prompt_parts(session))
|
|
321
328
|
end
|
|
322
329
|
# The per-session settings' chips (the info bar's ⚙ chip: llm ctx, think
|
|
323
330
|
# and reasoning; the tools chip): the worker's, else worked out here from the
|
|
@@ -361,7 +368,7 @@ module Samagotchi
|
|
|
361
368
|
state = tail && tail["session_state_snapshot"]
|
|
362
369
|
state = nil unless state.is_a?(Hash)
|
|
363
370
|
if state
|
|
364
|
-
status, used, notes = state.values_at("status", "used_memory_names", "prompt_notes")
|
|
371
|
+
status, used, notes, parts = state.values_at("status", "used_memory_names", "prompt_notes", "prompt_parts")
|
|
365
372
|
answer = tail["answer"]
|
|
366
373
|
cwd = tail_working_directory(id, tail, answer)
|
|
367
374
|
answer = without_file_refs(answer) unless cwd
|
|
@@ -371,9 +378,13 @@ module Samagotchi
|
|
|
371
378
|
status = displayed_status(session)
|
|
372
379
|
used = session.used_memory_names
|
|
373
380
|
notes = session.prompt_notes.map(&:to_h)
|
|
381
|
+
parts = saved_prompt_parts(session)
|
|
374
382
|
messages = last_assistant_for_display(session.messages, turn_id: turn_id, cwd: session.working_directory)
|
|
375
383
|
end
|
|
376
384
|
session_json = { id: id, status: status, used_memory_names: Array(used), prompt_notes: Array(notes) }
|
|
385
|
+
# A live worker's state without the key (an older worker) leaves it out:
|
|
386
|
+
# unknown, not none, so the page keeps the parts it has. No file read.
|
|
387
|
+
session_json[:prompt_parts] = parts if parts.is_a?(Array)
|
|
377
388
|
live_metrics = state && state["metrics"]
|
|
378
389
|
timing = recent_timing(id, live_metrics)
|
|
379
390
|
json_response(200, {
|
|
@@ -166,6 +166,13 @@ module Samagotchi
|
|
|
166
166
|
session.displayed_status(owner: owner)
|
|
167
167
|
end
|
|
168
168
|
|
|
169
|
+
def shown_status(session, state, turn_snapshot, owner:)
|
|
170
|
+
status = displayed_status(session, state, owner: owner)
|
|
171
|
+
return Session::STATUS_IDLE if status == Session::STATUS_RUNNING && turn_snapshot && !turn_snapshot["current_turn"]
|
|
172
|
+
|
|
173
|
+
status
|
|
174
|
+
end
|
|
175
|
+
|
|
169
176
|
def first_preview_for(session)
|
|
170
177
|
raw = session.first_preview || session.last_prompt || ""
|
|
171
178
|
norm = raw.to_s.gsub(/\s+/, " ").strip
|
|
@@ -292,7 +292,11 @@ module Samagotchi
|
|
|
292
292
|
# saves keep it.
|
|
293
293
|
def start_anytime_command(command)
|
|
294
294
|
@engine.spawn_anytime do
|
|
295
|
-
result = command_result(command)
|
|
295
|
+
result = command_result(command) do
|
|
296
|
+
@engine.running_anytime do
|
|
297
|
+
@commands.run(command.line, confirm: confirm?(command), as_parent: as_parent?(command), user_ui: user_ui?(command))
|
|
298
|
+
end
|
|
299
|
+
end
|
|
296
300
|
# Saved before its command_ran: a client that reads the file on the reply finds it.
|
|
297
301
|
save_or_log(:command) { save_session } unless Array(result.changed).empty?
|
|
298
302
|
announce_command(command, status: result.status.to_s, output: result.output, changed: Array(result.changed),
|
|
@@ -30,6 +30,7 @@ module Samagotchi
|
|
|
30
30
|
save_or_log(:interrupted_turn) { save_session }
|
|
31
31
|
end
|
|
32
32
|
|
|
33
|
+
# Statuses that can be stale before this worker handles its first turn.
|
|
33
34
|
# No turn runs yet: a status a turn would be behind is from before this
|
|
34
35
|
# worker, and goes idle under the lock (resume_session writes nothing to
|
|
35
36
|
# the file, which this worker owns): a stopped one with no stop marker
|
|
@@ -39,7 +40,6 @@ module Samagotchi
|
|
|
39
40
|
# prompt waits (WorkerInbound.initial_prompt_pending?).
|
|
40
41
|
STALE_STATUSES = [Session::STATUS_STOPPED, Session::STATUS_ERROR, Session::STATUS_RUNNING].freeze
|
|
41
42
|
|
|
42
|
-
#
|
|
43
43
|
# Saved whatever the status: the save stamps updated_at, which a resume
|
|
44
44
|
# used to move (an old session woken with no turn, an attach or a web
|
|
45
45
|
# wake, stays young for the sweep and moves up the lists). Not a
|
data/lib/samagotchi/worker.rb
CHANGED
|
@@ -150,6 +150,7 @@ module Samagotchi
|
|
|
150
150
|
@command_queue = Thread::Queue.new
|
|
151
151
|
# Set as it leaves: nothing happened in the session (#discard?).
|
|
152
152
|
@discard = false
|
|
153
|
+
@marked_leaving = false
|
|
153
154
|
# The lines the running turn's drain merged ([prompt, TurnOrigin]), for a
|
|
154
155
|
# failed prompt turn to hand back; reset as each turn begins.
|
|
155
156
|
@merged_this_turn = []
|
|
@@ -165,14 +165,17 @@ module Samagotchi
|
|
|
165
165
|
end
|
|
166
166
|
|
|
167
167
|
# Delete a session its worker left empty. Checked again now the lock is
|
|
168
|
-
# free
|
|
169
|
-
#
|
|
170
|
-
#
|
|
171
|
-
#
|
|
168
|
+
# free, and once more under the deleting lock (delete_session's
|
|
169
|
+
# still:): a note or input may have come in since the worker looked
|
|
170
|
+
# (one that went in before the lock keeps the session), and a worker
|
|
171
|
+
# woken meanwhile owns it (delete_session refuses). A delivery during
|
|
172
|
+
# the deleting lock is refused (DeliverResult::DELETING, its file taken
|
|
173
|
+
# back), one after removal finds no session.
|
|
172
174
|
private def discard_left_session(session_id, state_dir:, default_model:)
|
|
173
|
-
|
|
175
|
+
empty = -> { SessionManager.discardable?(session_id, state_dir: state_dir, default_model: default_model) }
|
|
176
|
+
return unless empty.call
|
|
174
177
|
|
|
175
|
-
SessionManager.delete_session(session_id, state_dir: state_dir, purge_runs: false)
|
|
178
|
+
SessionManager.delete_session(session_id, state_dir: state_dir, purge_runs: false, still: empty)
|
|
176
179
|
Log.info(:worker, "discarded_empty", sid: session_id)
|
|
177
180
|
rescue SessionManager::DeleteRefused, SessionManager::OwnedByTUI, ArgumentError, SystemCallError => e
|
|
178
181
|
Log.info(:worker, "kept_session", sid: session_id, error: e.class.name, msg: e.message)
|
|
@@ -78,6 +78,10 @@ module Samagotchi
|
|
|
78
78
|
# nothing else may resume, stop or delete it.
|
|
79
79
|
def tui_owned? = owner&.tui? == true
|
|
80
80
|
|
|
81
|
+
# A deleter holds it (OwnerLock kind deleting: SessionManager's
|
|
82
|
+
# delete, an empty session's discard) while the session's files go.
|
|
83
|
+
def deleting? = owner&.deleting? == true
|
|
84
|
+
|
|
81
85
|
# The `<id>/stopped` marker: a user's stop, not the turn's status.
|
|
82
86
|
def stop_marked? = stop_marked
|
|
83
87
|
|
|
@@ -53,8 +53,24 @@ module Samagotchi
|
|
|
53
53
|
# its outputs), whatever the strategy; +has_drop+ whether any of its
|
|
54
54
|
# content outputs holds the user's applied drop (an undrop has
|
|
55
55
|
# something to take back: a forgotten item too, its other outputs
|
|
56
|
-
# stubbed by the model's layers)
|
|
57
|
-
|
|
56
|
+
# stubbed by the model's layers); +scope+ a memory's: the scope its
|
|
57
|
+
# latest memory_read answered from (its stamp's file), nil for one only
|
|
58
|
+
# written or read before memory stamps. The set has one item per name,
|
|
59
|
+
# so a session that read both a project x and a system x has one item
|
|
60
|
+
# with the latest read's scope.
|
|
61
|
+
Item = Data.define(:kind, :key, :state, :tokens, :ops, :count, :first_id, :pinned, :has_drop, :scope) do
|
|
62
|
+
def initialize(kind:, key:, state:, tokens:, ops:, count:, first_id:, pinned:, has_drop:, scope: nil)
|
|
63
|
+
super
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# The JSON the event and the route carry: scope only for a memory
|
|
67
|
+
# that has one (the page matches it with the prompt's parts).
|
|
68
|
+
def to_h
|
|
69
|
+
hash = super
|
|
70
|
+
hash.delete(:scope) unless kind == MEMORY && scope
|
|
71
|
+
hash
|
|
72
|
+
end
|
|
73
|
+
end
|
|
58
74
|
|
|
59
75
|
# An item the user added (/working-set add) that the next turn's note
|
|
60
76
|
# asks the model to read: its identity (+kind+, +key+, as an Item's)
|
|
@@ -511,7 +527,19 @@ module Samagotchi
|
|
|
511
527
|
LIVE
|
|
512
528
|
end
|
|
513
529
|
Item.new(kind: kind, key: key, state: state, tokens: tokens, ops: group.map(&:op).uniq, count: group.size,
|
|
514
|
-
first_id: first.run.ref.id, pinned: pinned, has_drop: contents.any? { |touch| dropped?(touch, conversation) }
|
|
530
|
+
first_id: first.run.ref.id, pinned: pinned, has_drop: contents.any? { |touch| dropped?(touch, conversation) },
|
|
531
|
+
scope: kind == MEMORY ? memory_item_scope(key, group, conversation) : nil)
|
|
532
|
+
end
|
|
533
|
+
|
|
534
|
+
# The scope a memory's latest memory_read answered from, by its stamp's
|
|
535
|
+
# file (no memory text read); nil for a memory only written or read
|
|
536
|
+
# before memory stamps. The stamp lookup the stale check does already.
|
|
537
|
+
def memory_item_scope(key, group, conversation)
|
|
538
|
+
touch = group.reverse_each.find { |each| each.op == "read" }
|
|
539
|
+
entries = touch && memory_entries(touch.run, conversation)
|
|
540
|
+
entry = entries && entries[key]
|
|
541
|
+
path = entry.is_a?(Hash) ? field(entry, :path).to_s : ""
|
|
542
|
+
path.empty? ? nil : memory_scope(path)
|
|
515
543
|
end
|
|
516
544
|
|
|
517
545
|
# Whether the model is still sent +touch+'s output: whole (with the
|
|
@@ -620,6 +648,6 @@ module Samagotchi
|
|
|
620
648
|
:changed?, :memory_changed?, :same_path?, :differs?, :stamp_hash, :stamp_of, :field, :event, :body_of,
|
|
621
649
|
:lines_of, :saved_diff, :memory_entries, :memory_paths?, :project_dir_within_root?,
|
|
622
650
|
:resolution_metadata?, :resolve_memory, :resolved_memory_entry, :memory_part, :overlay_tail,
|
|
623
|
-
:memory_scope, :memory_body
|
|
651
|
+
:memory_scope, :memory_body, :memory_item_scope
|
|
624
652
|
end
|
|
625
653
|
end
|
|
@@ -33,7 +33,7 @@ module Samagotchi
|
|
|
33
33
|
WorkingSetSteer::ADD => "added", WorkingSetSteer::UNADD => "unadded" }.freeze
|
|
34
34
|
PIN_OPS = [WorkingSetSteer::PIN, WorkingSetSteer::UNPIN].freeze
|
|
35
35
|
|
|
36
|
-
# @param engine [Engine] #session, #working_set_strategy,
|
|
36
|
+
# @param engine [Engine] #session, #working_set_strategy, #prompt_memories,
|
|
37
37
|
# #clone_messages, #replace_messages
|
|
38
38
|
# @param save [#call] saves the session after a change
|
|
39
39
|
def initialize(engine:, save:)
|
|
@@ -110,7 +110,8 @@ module Samagotchi
|
|
|
110
110
|
when WorkingSetSteer::PIN then WorkingSetSteer.pin(messages, pins, target, strategy: strategy, cwd: cwd)
|
|
111
111
|
when WorkingSetSteer::UNPIN then WorkingSetSteer.unpin(pins, target)
|
|
112
112
|
when WorkingSetSteer::ADD
|
|
113
|
-
WorkingSetSteer.add(messages, target, strategy: strategy, cwd: cwd, found: method(:missing)
|
|
113
|
+
WorkingSetSteer.add(messages, target, strategy: strategy, cwd: cwd, found: method(:missing),
|
|
114
|
+
in_prompt: @engine.prompt_memories)
|
|
114
115
|
else WorkingSetSteer.unadd(messages, target)
|
|
115
116
|
end
|
|
116
117
|
end
|
|
@@ -86,6 +86,7 @@ module Samagotchi
|
|
|
86
86
|
not_http: "not an http(s) URL: web_fetch can't fetch it",
|
|
87
87
|
already_sent: "already in the model's context (sent whole): nothing to add",
|
|
88
88
|
already_added: "already added: the next turn reads it",
|
|
89
|
+
in_prompt: "already in the system prompt: nothing to add",
|
|
89
90
|
not_added: "not added (no add of it is pending)"
|
|
90
91
|
}.freeze
|
|
91
92
|
|
|
@@ -258,11 +259,13 @@ module Samagotchi
|
|
|
258
259
|
# Adds +target+: the next turn's note asks the model to read it. +found+
|
|
259
260
|
# answers whether the item exists (a file, a memory; the caller's
|
|
260
261
|
# look). Refused for an item the model is sent whole now (live, a read
|
|
261
|
-
# of it sent), a dropped one (undrop it), and one
|
|
262
|
+
# of it sent), a dropped one (undrop it), a prompt-only memory, and one
|
|
263
|
+
# added already.
|
|
262
264
|
# @param found [#call] target → nil when it exists, else a Refused reason
|
|
265
|
+
# @param in_prompt [Array<Array(String, String, nil)>] memory names and scopes the system prompt holds
|
|
263
266
|
# @return [Done]
|
|
264
267
|
# @raise [Refused]
|
|
265
|
-
def add(conversation, target, strategy:, cwd:, found: ->(_) {})
|
|
268
|
+
def add(conversation, target, strategy:, cwd:, found: ->(_) {}, in_prompt: [])
|
|
266
269
|
raise Refused, :already_added if pending?(conversation, ADD, target)
|
|
267
270
|
|
|
268
271
|
reason = target.kind == WorkingSet::URL && !target.key.match?(%r{\Ahttps?://}i) ? :not_http : found.call(target)
|
|
@@ -270,6 +273,7 @@ module Samagotchi
|
|
|
270
273
|
|
|
271
274
|
outputs = WorkingSet.outputs_of(conversation, kind: target.kind, key: target.key, strategy: strategy, cwd: cwd)
|
|
272
275
|
raise Refused, :undrop_first if outputs.any? { |output| drop_of(conversation, output) }
|
|
276
|
+
raise Refused, :in_prompt if outputs.empty? && prompt_memory?(target, in_prompt)
|
|
273
277
|
raise Refused, :already_sent if outputs.any?(&:sent) && live?(conversation, target, strategy, cwd)
|
|
274
278
|
|
|
275
279
|
Done.new(target: target, op: ADD, ids: [], freed_chars: 0, tail_chars: 0, free: true)
|
|
@@ -366,6 +370,12 @@ module Samagotchi
|
|
|
366
370
|
entry["op"] == op && entry["kind"] == target.kind && entry["key"] == target.key
|
|
367
371
|
end
|
|
368
372
|
|
|
373
|
+
def prompt_memory?(target, names)
|
|
374
|
+
return false unless target.kind == WorkingSet::MEMORY
|
|
375
|
+
|
|
376
|
+
Tools::MemoryRead.prompt_memory?(target.key, names)
|
|
377
|
+
end
|
|
378
|
+
|
|
369
379
|
# The note listing +ops+: a tail system message, escaped like a context
|
|
370
380
|
# note (Prompt::ESCAPED_KINDS: it carries paths and URLs).
|
|
371
381
|
def note(ops)
|
|
@@ -409,6 +419,7 @@ module Samagotchi
|
|
|
409
419
|
tokens >= 1000 ? format("%.1fk tokens", tokens / 1000.0) : "#{tokens} tokens"
|
|
410
420
|
end
|
|
411
421
|
|
|
412
|
-
private_class_method :relative, :shared_with, :drop_of, :known?, :live?, :layers, :same?, :
|
|
422
|
+
private_class_method :relative, :shared_with, :drop_of, :known?, :live?, :layers, :same?, :prompt_memory?,
|
|
423
|
+
:labels, :call_of
|
|
413
424
|
end
|
|
414
425
|
end
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: samagotchi
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.177.1
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Dmitry Dedov
|
|
@@ -169,6 +169,7 @@ files:
|
|
|
169
169
|
- docs/internals/participants.md
|
|
170
170
|
- docs/internals/prompt-caching.md
|
|
171
171
|
- docs/internals/remote-sessions.md
|
|
172
|
+
- docs/internals/session-lifecycle.md
|
|
172
173
|
- docs/internals/tool-output-limits.md
|
|
173
174
|
- docs/internals/web-frontend.md
|
|
174
175
|
- docs/internals/web-push.md
|
|
@@ -622,6 +623,7 @@ files:
|
|
|
622
623
|
- lib/samagotchi/prompt_history.rb
|
|
623
624
|
- lib/samagotchi/prompt_literal_guard.rb
|
|
624
625
|
- lib/samagotchi/prompt_note.rb
|
|
626
|
+
- lib/samagotchi/prompt_part.rb
|
|
625
627
|
- lib/samagotchi/prompt_warmup.rb
|
|
626
628
|
- lib/samagotchi/proxy_trace.rb
|
|
627
629
|
- lib/samagotchi/push_command.rb
|
|
@@ -687,6 +689,10 @@ files:
|
|
|
687
689
|
- lib/samagotchi/session_field.rb
|
|
688
690
|
- lib/samagotchi/session_inbox.rb
|
|
689
691
|
- lib/samagotchi/session_inbox_delivery.rb
|
|
692
|
+
- lib/samagotchi/session_lifecycle.rb
|
|
693
|
+
- lib/samagotchi/session_lifecycle/allowed.rb
|
|
694
|
+
- lib/samagotchi/session_lifecycle/canonical.rb
|
|
695
|
+
- lib/samagotchi/session_lifecycle/reading.rb
|
|
690
696
|
- lib/samagotchi/session_manager.rb
|
|
691
697
|
- lib/samagotchi/session_manager/delivery.rb
|
|
692
698
|
- lib/samagotchi/session_manager/emptiness.rb
|
|
@@ -964,6 +970,7 @@ files:
|
|
|
964
970
|
- lib/samagotchi/web/public/context_chips.js
|
|
965
971
|
- lib/samagotchi/web/public/copy.js
|
|
966
972
|
- lib/samagotchi/web/public/ctx.js
|
|
973
|
+
- lib/samagotchi/web/public/ctx_tokens.js
|
|
967
974
|
- lib/samagotchi/web/public/data.js
|
|
968
975
|
- lib/samagotchi/web/public/delete_sheet.js
|
|
969
976
|
- lib/samagotchi/web/public/delivery_line.js
|
|
@@ -1142,6 +1149,7 @@ files:
|
|
|
1142
1149
|
- lib/samagotchi/web/public/ws_peek.js
|
|
1143
1150
|
- lib/samagotchi/web/public/ws_preview.css
|
|
1144
1151
|
- lib/samagotchi/web/public/ws_reader.js
|
|
1152
|
+
- lib/samagotchi/web/public/ws_sections.js
|
|
1145
1153
|
- lib/samagotchi/web/public/ws_timeline.js
|
|
1146
1154
|
- lib/samagotchi/web/public/ws_way_in.js
|
|
1147
1155
|
- lib/samagotchi/web/public_url.rb
|