samagotchi 0.48.0 → 0.49.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b751e52e486a5e301e85e8dd0557b9786fc240d59becf71152eaee6b97c2176e
4
- data.tar.gz: 1be48dc0d3898135b44b56bab594ee4af910669512b584c6d408536ed14f47bb
3
+ metadata.gz: ca248891309ffde628ce6c03c2bbd35fa946f7fa669978c30d1478a0f236a920
4
+ data.tar.gz: 50e85c20fa0882c5caeeaf7a2c141dd46a443c5f725d60120e194ada9152871c
5
5
  SHA512:
6
- metadata.gz: 0b3d59478632ccee06384d6844b7a7e5d21dcc0e90042056d305a4763272f0ed1b1d0e9c7559fe7296915bc07c62148417883ad7084c18c488bd5d522f1e7f72
7
- data.tar.gz: 726ae060c0f5f0b0c9238b24aa15601431b0648e297cba8709e9943f1e257da447009bea82b669178c859080ed79d2a25dc60ccc805b429f95bf0e7b0ba36839
6
+ metadata.gz: e6ce68e65e80c48433bdb55706aaa19790ab6a140f81550f63420c1f4574d1e423a2dd356a01fda3534234331eacfb9a03151e3fa83b602d027d039ad44c76ab
7
+ data.tar.gz: a476e538ff5913c82625a18c8e23b822bc402f7ed206724debe65c95863a1ab7ab2606823befae4c44a0e265b3a8a45eafcf08c6b2215a27dab4bd6c03ac98ec
data/CHANGELOG.md CHANGED
@@ -8,6 +8,37 @@ and commands may change between minor versions. How releases are made:
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.49.0] - 2026-10-09
12
+
13
+ ### Added
14
+
15
+ - Native Gemma 4 on llama.cpp (with `--mmproj`) sees images: `@path`, `read` on an image and the web's pasted images
16
+ reach it, as they do Qwen 3.6. Before, chi refused with "profile gemma4 has no image template yet".
17
+ - Plugins: `ctx.frontend` says what runs the session: `:repl` (the REPL, `-p` without `--non-interactive`),
18
+ `:one_shot` (`-p --non-interactive`) or `:worker` (a session worker: the web, an attached TUI).
19
+
20
+ ### Changed
21
+
22
+ - github-pr 0.4.0: line links read the PR's files (`gh api`) only in a session worker (the web, an attached chi), not
23
+ in the REPL, `chi -p` or a scratch session, whose answers no web page shows while they run. `bundles: github-pr:
24
+ line_links: always` reads in the REPL and `-p` too; `false` still turns it off. The PR lookup and attach are
25
+ unchanged. See [Line links](docs/context.md#line-links).
26
+
27
+ ### Fixed
28
+
29
+ - Web: a command queued mid-turn (`/model X`) shows its bubble after the turn's answer once it runs, not among the
30
+ turn's rows above the answer.
31
+ - A background task whose process exited and whose pid another process reused since no longer reads as running in
32
+ `task_list`, `task_get` and `task_wait` until a `task_stop`: each read checks the process's start time.
33
+ - A continue that died after noting its moved delegates no longer notes them again when the new link's worker
34
+ finishes the move: `move.json` records who was told.
35
+ - An attached chi watching a `-p --non-interactive` run says a question there was dismissed because no one could
36
+ answer it (`(dismissed: no one to answer in a non-interactive run)`), as the run itself does, not
37
+ `(question cancelled)`.
38
+
39
+ Update with `chi update`: it updates github-pr (0.4.0: line links only where the web can show them). If you set
40
+ `line_links: true` to get links in the REPL, set `line_links: always` instead.
41
+
11
42
  ## [0.48.0] - 2026-10-09
12
43
 
13
44
  ### Changed
@@ -2231,7 +2262,8 @@ and long-lived sessions.
2231
2262
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
2232
2263
  hotkey panel that send selected text or the clipboard to your sessions.
2233
2264
 
2234
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.48.0...HEAD
2265
+ [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.49.0...HEAD
2266
+ [0.49.0]: https://github.com/dm1try/samagotchi/compare/v0.48.0...v0.49.0
2235
2267
  [0.48.0]: https://github.com/dm1try/samagotchi/compare/v0.47.0...v0.48.0
2236
2268
  [0.47.0]: https://github.com/dm1try/samagotchi/compare/v0.46.1...v0.47.0
2237
2269
  [0.46.1]: https://github.com/dm1try/samagotchi/compare/v0.46.0...v0.46.1
@@ -904,7 +904,7 @@ Whether a model can see images is found out before a turn with images is sent:
904
904
 
905
905
  - a native llama.cpp host: `/props` must report `modalities.vision` (the server
906
906
  runs with `--mmproj`) and a media marker, and the prompt profile must know the
907
- chat template's image wrapping (qwen36 does; gemma4 not yet);
907
+ chat template's image wrapping (qwen36 and gemma4 do);
908
908
  - mlx and oMLX hosts: no (not verified with recent chi versions);
909
909
  - an OpenAI-API host: a local llama.cpp's `/props`, else the host's model list
910
910
  (OpenRouter's `architecture.input_modalities`); when it doesn't say, the image
data/docs/context.md CHANGED
@@ -258,13 +258,20 @@ show the answer as it is.
258
258
  So the first answer of a very short turn may come without links, and
259
259
  after a push links may be a few lines off until the next read. Without
260
260
  `gh` or its login, nothing is linked.
261
+ - **Where it reads**: only in a session worker (the web, an attached chi),
262
+ whose answers the web shows while the session runs. The REPL and
263
+ `chi -p` read nothing (no `gh api` calls), so their answers have no links,
264
+ in the web too; a scratch session never reads. The PR itself is still
265
+ attached and its context still reaches the model everywhere.
261
266
 
262
- Turn it off:
267
+ `line_links:` takes `false` (off), `true` (the default: a worker only) or
268
+ `always` (the REPL and `chi -p` read too, so their answers are linked when
269
+ you open the session in the web later):
263
270
 
264
271
  ```yaml
265
272
  bundles:
266
273
  github-pr:
267
- line_links: false
274
+ line_links: false # or always
268
275
  ```
269
276
 
270
277
  ## Safety
@@ -19,7 +19,7 @@ Behavior:
19
19
 
20
20
  - `execute`, `task_create` and the `!cmd` shell bang run the command in a non-login shell: `/bin/sh -c` on Linux; on macOS, when `/bin/zsh` is there, `/bin/zsh --emulate sh +o ignore_braces +o sh_glob -o bash_rematch +o bsd_echo -c` (macOS's `/bin/sh` is bash 3.2, which can't parse an apostrophe in a heredoc inside `"$( )"`, the usual commit message shape). That mode reads no rc files and keeps POSIX word splitting, unmatched globs left as is, `{1..3}`, `[[ … =~ (…) ]]` with `BASH_REMATCH`, arrays, `$'…'`, `&>` and echo expanding `\t`. Bash-only builtins and variables (`shopt`, `BASH_VERSION`, `${!prefix*}`, `read -p`) are not there.
21
21
  - Task metadata and output are persisted under `tmp/tasks/`.
22
- - A task record keeps its process's pid and start time (`pid_started`). Before `task_stop` signals, the pid must still lead its own process group and must not have started at another time; otherwise the pid was reused by another process, nothing is signalled and the task ends as failed. A start time that can't be read at that moment (a failed `ps`) falls back to the group check, as does a record without `pid_started` (from an older chi). `task_get`, `task_list` and `task_wait`'s polls check the group only (no `ps` per poll).
22
+ - A task record keeps its process's pid and start time (`pid_started`). Before `task_stop` signals, the pid must still lead its own process group and must not have started at another time; otherwise the pid was reused by another process, nothing is signalled and the task ends as failed. A start time that can't be read at that moment (a failed `ps`) falls back to the group check, as does a record without `pid_started` (from an older chi). `task_get`, `task_list`, `task_wait`'s polls and the running-task lists (a cancelled turn's note, a worker's idle exit) make the same check, so a task whose pid was reused reads as exited (failed) at once, not as running until a `task_stop`; on macOS that is one `ps` per running task per check (~5 ms).
23
23
  - Task listing is workspace-scoped (current project only).
24
24
  - `task_get` returns metadata and `output_path`; use `read` for output contents.
25
25
  - `task_wait` accepts `timeout`, `tail_lines` (maximum 100), and `done_pattern` (a regular expression string).
data/docs/plugins.md CHANGED
@@ -505,6 +505,7 @@ full label, `plugin.rb (bundle my-bundle)`.
505
505
  | `ctx.repo_root` | the git checkout holding `cwd`, or nil |
506
506
  | `ctx.scratch?` | whether the session is a `chi scratch` one (deleted when it ends) |
507
507
  | `ctx.delegate?` | whether the session is a delegate child: a task another session handed over |
508
+ | `ctx.frontend` | what runs the session, read now: `:repl` (the REPL, `-p` without `--non-interactive`), `:one_shot` (`-p --non-interactive`: one turn, then exit) or `:worker` (a session worker: the web, an attached TUI). Only a worker's answers reach the web while it runs; a REPL's show there once the session is opened. Until the host sets it (while the plugins load, inside `Engine.new`) it reads `:one_shot`, so read it in hooks and init tasks, not in `register` |
508
509
  | `ctx.fork?` | whether the session is a fork (`ctx.sessions.fork`): it has a parent but isn't a delegate child, and started from a conversation, so its first prompt isn't its first user message |
509
510
  | `ctx.model` | the model the session runs on now: its resolved ref (`host:id`), right after `/model` too |
510
511
  | `ctx.model_key` | that model's memory overlay key (`<name>.<key>.md`, what `memory_write current_model_only` writes) |
@@ -1240,8 +1241,9 @@ nothing without `gh`, a repository or an open PR), and resolves PR URLs for
1240
1241
  `chi context add` and the web's "+ URL". Its script prints the PR as text
1241
1242
  and a summary of what changed in counts, authors and states only; it wakes
1242
1243
  the session for a review requesting changes, checks turning red, or the PR
1243
- merged or closed. In the web, a `path:line` in an answer links to that line
1244
- of the session's PR ([Line links](context.md#line-links)). `auto_attach:
1244
+ merged or closed. In the web, a `path:line` in a worker's answer links to
1245
+ that line of the session's PR ([Line links](context.md#line-links); `line_links:
1246
+ always` for the REPL and `chi -p` too). `auto_attach:
1245
1247
  offer` asks with a card first (`/pr-attach N`, `/pr-decline N`), `off`
1246
1248
  attaches nothing ([Attach, offer or off](context.md#attach-offer-or-off)).
1247
1249
  See [Attached context](context.md#github-prs-the-github-pr-bundle).
data/docs/sessions.md CHANGED
@@ -197,7 +197,7 @@ A session can **continue** an earlier one: "the next day of the same routine" (a
197
197
  - **The recap first:** a previous link with a live worker is asked for a recap (the Bridge's `POST /recap`) and given up to 30 s to write it; one with none wrote its recap when its worker left.
198
198
  - **The previous link is archived** before the new one starts, by the archive's own rules (see *Archiving a session*): a turn running, a prompt queued or the step-limit question refuse it, a live idle worker is stopped, a plain REPL's session is refused. Its finished delegates are archived with it, as any archive does.
199
199
  - **Its open delegates move to the new link** instead: each direct delegate that is running, waiting for an answer, has a live worker or a reply its parent wasn't given, or has such a delegate below it (checked again after the recap wait, so one delegated meanwhile moves too). It moves with its own delegates, stays unarchived, and from then on is the new link's: its card folds under the new link, its reports ring the new link (an idle one runs a wake turn for them, as for its own delegates), `delegate_result` and the `⑂` chip count it there, and what its parent was already told (`delegates.json`) and any report still waiting come along, so nothing is reported twice. A moved delegate gets a context note from `session chain`, `Your parent session is now 4b7e9a01 (…), the next link of its session chain: …`, as its system prompt keeps naming the parent it started with. The move writes `<child>/parent.json` (`{parent_id, from, at}`) beside the child's session file, never the file itself, so a live child worker saving its own copy changes nothing; every reader applies it (a later move overwrites it; it is never removed). A continue is **refused for an open delegate that can't move** (`ContinueRefused`, naming it): one whose live worker runs an older chi (`older chi worker 0.46.1; restart it`: `chi sessions restart <id>`, or stop it) or that is open in a chi REPL (close it there). An older `chi web` or CLI still running shows a moved delegate under the archived link until it is restarted.
200
- - **If the continue fails part-way:** a new link that fails to start gives its moved delegates back before it is deleted (each gets a note saying so; its worker is stopped first, if one started, and a worker that won't stop is reported, the link left), with any report one of them rang it with meanwhile; the previous link, back in the lists, is woken for reports waiting. A continue that dies in the middle leaves a `move.json` in the new link's folder: the new link's next worker finishes that move (only the delegates it names) as it starts. Until the new link's own worker holds it, a ring from a moved delegate doesn't start another (a `starting` marker in its folder, which that worker removes; a stale one, over 60 s old or from a process that is gone, is ignored). An open delegate below an archived delegate refuses the continue (`under archived …`): unarchive that one, or archive this one.
200
+ - **If the continue fails part-way:** a new link that fails to start gives its moved delegates back before it is deleted (each gets a note saying so; its worker is stopped first, if one started, and a worker that won't stop is reported, the link left), with any report one of them rang it with meanwhile; the previous link, back in the lists, is woken for reports waiting. A continue that dies in the middle leaves a `move.json` in the new link's folder: the new link's next worker finishes that move (only the delegates it names, and without a second note to one already told) as it starts. Until the new link's own worker holds it, a ring from a moved delegate doesn't start another (a `starting` marker in its folder, which that worker removes; a stale one, over 60 s old or from a process that is gone, is ignored). An open delegate below an archived delegate refuses the continue (`under archived …`): unarchive that one, or archive this one.
201
201
  - **Refused too:** a link that is continued already (naming the link that continues it; continue that one, or `last:<id>`), a previous link whose folder is gone, and one whose model names a host config.yml no longer has. A refusal starts nothing and archives nothing; a new link that fails to start puts back what was archived. Every refusal that can be known up front (the archive's ones included) comes before the recap wait. One continue of a session runs at a time (a lock in its folder; other chains don't wait), so a double click finds the first one's link and is refused, while a `last:<id>` continue that waited follows the chain to its new end.
202
202
  - **Web:** `POST /api/sessions` takes `continues: "<id, prefix or last:id>"`, with `idle: true` (a new link waiting for its first message, previewed by the previous link's, or `preview`) or a `prompt`, and not `dir`, `model` or `llm_context` (400 `invalid_continues`: the previous link's are taken). 201 is the new session's summary, `continues` set, with `moved`: the ids of the delegates that moved to it (`[]` for none); 404 `not_found`; 400 `ambiguous_id` for a prefix of several sessions, `invalid_model` for a model whose host is gone; 409 `continued` with `next_id` (the link that continues it already, which the page opens instead), `open_children` with `ids` (open delegates that can't move), `folder_gone`, `busy`, `scratch` or `owned_by_tui`. Every session summary carries `continues`.
203
203
  - **The page:** the info bar's `continue →` continues the open session (`continues: <id>, idle: true`; it reads `continuing…` through the recap wait) and opens the new link with `Continue where we left off.` in the composer, not sent (the same line for every chain; a draft already there stays instead); the previous link is archived, a toast says so (`Continued 3fa2c1d0 in 4b7e9a01; 3fa2c1d0 is archived; 1 open delegate moved`), and a moved delegate's card folds under the new link. A link continued already has no `continue →`: its `→` link goes to the next link (a stale page's continue answered 409 `continued` opens `next_id`). A continue refused for open delegates that can't move shows a toast that names each one (its preview and what the server says to do: `older chi worker 0.46.1; restart it`, `open in a chi REPL; close it there`), each a link to its page; any other refusal shows the server's words. The info bar of a link carries `← 2026-10-08` (the previous link's day) and, on an earlier link, `2026-10-10 →`, each a link with its preview and id in the tooltip. A link whose title is the opener and nothing else (its first message once sent) shows its chain's first link's title instead, on its card, in the popover and in its info bar's title line, display only (its messages and data keep the opener; its own title when the first link is gone). The lists fold a chain into the card of its latest listed link, whatever the earlier links' archived state (typing in an archived link brings it back, folded there still), their delegates with them: the card's `↩ day N` chip (`day N of M` when later links aren't listed) opens a popover of the other links, newest first (`day N`, its date, its recap's first sentence or its preview, `archived`), a click opens one; the chip shows a live dot or `waiting` for a link that has a worker or waits on the user, and a waiting link puts its chain's card first. All sessions folds nothing while a search is typed or "include archived" is on: every link is a card of its own then, its chip `day N of M`, with its own delegates folded in, so a search finds an earlier link and its delegates.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: github-pr
3
- version: 0.3.3
3
+ version: 0.4.0
4
4
  scope: system
5
5
  description: Attaches the branch's open GitHub pull request to a session as context (and any PR URL with chi context add or the web's "+ URL"); the agent gets a note when reviews, comments, checks or its state change; in the web, a path:line in an answer links to that line of the PR; the auto_attach setting can offer the PR with a card first, or attach nothing
6
6
  trust_level: reviewed
@@ -11,7 +11,7 @@ needs:
11
11
  hint: brew install gh, then gh auth login
12
12
  plugin:
13
13
  file: plugin.rb
14
- sha256: sha256:f68b53bfb552e35c9b151ee42cc10c07923481fc3d5496f023422e388df6719a
14
+ sha256: sha256:2510f8e5bfc77b2a6343b47d56bf6be9da09fd8741f52928462945a55d83f0ce
15
15
  scripts:
16
16
  pr_context.rb: sha256:a883d2780e89c68c0d7b6d5e0fcb22c273f17bb167e79064e0e99db6bd2ee6f0
17
17
  context_providers:
@@ -23,8 +23,11 @@ require "tmpdir"
23
23
  # model's text stays as it was. The after_turn hook links from a per-PR
24
24
  # cache and never runs gh (the web holds the answer until the hooks are
25
25
  # done); before_turn, before_generation and the init task fill the cache
26
- # off the turn's thread. `bundles: github-pr: line_links: false` turns it
27
- # off.
26
+ # off the turn's thread (`gh api`), in a session worker only: the REPL and
27
+ # -p --non-interactive show no web page while they run (ctx.frontend; a chi
28
+ # without it counts as a worker), and a scratch session never fetches.
29
+ # `bundles: github-pr: line_links:` false turns it off, "always" fetches in
30
+ # the REPL and -p too (still not for a scratch session).
28
31
  #
29
32
  # `bundles: github-pr: auto_attach:` says what the init task does with the
30
33
  # branch's open PR: `attach` (the default), `offer` (a card with Attach and
@@ -37,6 +40,8 @@ class Plugin
37
40
  COMMAND_SECONDS = 20
38
41
  # before_generation looks for a newly attached PR at most this often.
39
42
  GENERATION_CHECK_SECONDS = 30
43
+ # line_links' values: off, a worker's only (the default), every frontend.
44
+ LINE_LINKS_MODES = { false => :off, true => :worker, "always" => :always }.freeze
40
45
  # auto_attach's values (YAML's bare true/false: attach/off).
41
46
  AUTO_ATTACH_MODES = { "attach" => :attach, "offer" => :offer, "off" => :off, true => :attach, false => :off }.freeze
42
47
  # /pr-attach and /pr-decline take a PR number (`42` or `#42`).
@@ -50,6 +55,7 @@ class Plugin
50
55
  @cache = PrCache.new
51
56
  @generation_checked_at = nil
52
57
  @warned_mode = false
58
+ @warned_line_links = false
53
59
  end
54
60
 
55
61
  def register(chi)
@@ -58,13 +64,13 @@ class Plugin
58
64
  # Inline (an init task has its own thread), whatever the attach
59
65
  # returned (attached already, a child, a scratch session), and after
60
66
  # it, so a PR it just attached is warm for the first answer.
61
- refresh(ctx, attached_prs(ctx)) if line_links?(ctx)
67
+ refresh(ctx, attached_prs(ctx)) if prefetch?(ctx)
62
68
  summary
63
69
  end
64
70
  chi.on(:before_turn) do |event, ctx|
65
71
  # The prompt too: messages is the history before this turn, and a
66
72
  # delegate child's task is its first prompt.
67
- kick(ctx, attached_prs(ctx) + PrRef.from_messages(event[:messages], prompt: event[:prompt])) if line_links?(ctx)
73
+ kick(ctx, attached_prs(ctx) + PrRef.from_messages(event[:messages], prompt: event[:prompt])) if prefetch?(ctx)
68
74
  log_first_prompt(event, ctx)
69
75
  end
70
76
  chi.command("/pr-attach", "Attach the PR this session was offered: /pr-attach 42", anytime: true) do |args, ctx|
@@ -150,7 +156,34 @@ class Plugin
150
156
 
151
157
  private
152
158
 
153
- def line_links?(ctx) = ctx.settings["line_links"] != false
159
+ # `bundles: github-pr: line_links:`: :off, :worker (true or unset) or
160
+ # :always; an unknown value (a quoted "false") is :worker, logged once.
161
+ def line_links_mode(ctx)
162
+ value = ctx.settings["line_links"]
163
+ return :worker if value.nil?
164
+
165
+ LINE_LINKS_MODES.fetch(value.is_a?(String) ? value.strip.downcase : value) do
166
+ ctx.log.warn(:pr_line_links_unknown, value: value.to_s[0, 40]) unless @warned_line_links
167
+ @warned_line_links = true
168
+ :worker
169
+ end
170
+ end
171
+
172
+ def line_links?(ctx) = line_links_mode(ctx) != :off
173
+
174
+ # Whether to fetch PR data for line links (gh api): not for a scratch
175
+ # session (gone at exit), and by default only in a session worker, the
176
+ # one frontend whose answers the web shows while it runs. A chi before
177
+ # ctx.frontend (0.49.0) counts as a worker.
178
+ def prefetch?(ctx)
179
+ return false if ctx.scratch?
180
+
181
+ case line_links_mode(ctx)
182
+ when :off then false
183
+ when :always then true
184
+ else (ctx.respond_to?(:frontend) ? ctx.frontend : :worker) == :worker
185
+ end
186
+ end
154
187
 
155
188
  def offer_card_id(number) = "github-pr-offer-#{number}"
156
189
 
@@ -275,7 +308,7 @@ class Plugin
275
308
  # A PR attached while the turn runs (a parent attaching it right after
276
309
  # `delegate wait: false`), checked at most every GENERATION_CHECK_SECONDS.
277
310
  def check_attached(ctx)
278
- return unless line_links?(ctx)
311
+ return unless prefetch?(ctx)
279
312
  return if @generation_checked_at && now - @generation_checked_at < GENERATION_CHECK_SECONDS
280
313
 
281
314
  @generation_checked_at = now
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.48.0
3
+ version: 0.49.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
@@ -30,7 +30,7 @@ module Samagotchi
30
30
  # until it is done: a worker that starts and finds one finishes the move
31
31
  # (#adopt), and a failed continue moves the same children back.
32
32
  module ChildMove
33
- # <new link dir>/move.json: {from, ids}, while a move is under way.
33
+ # <new link dir>/move.json: {from, ids, noted}, while a move is under way.
34
34
  INTENT_FILE = "move.json"
35
35
  # <new link dir>/starting: {pid, at}, from the move to the worker's spawn.
36
36
  STARTING_FILE = "starting"
@@ -47,8 +47,11 @@ module Samagotchi
47
47
  # link, their subtrees with them), +refuse+ the open ones it can't move
48
48
  # (SessionManager::OpenChild, why: an older chi worker or a chi REPL).
49
49
  Plan = Data.define(:move, :refuse)
50
- # A move under way: from the session, the children moved.
51
- Intent = Data.define(:from, :ids)
50
+ # A move under way: from the session, the children moved, and those
51
+ # already sent their note (so a move finished again notes no one twice).
52
+ Intent = Data.define(:from, :ids, :noted) do
53
+ def initialize(from:, ids:, noted: []) = super
54
+ end
52
55
 
53
56
  module_function
54
57
 
@@ -100,16 +103,26 @@ module Samagotchi
100
103
  # Move +ids+ (direct children of +from+) to +to+: the intent, the
101
104
  # cursors +to+ lacks (delegates.json), the overrides, the rings waiting
102
105
  # in +from+'s children/, a note to each child, then the intent goes.
103
- # Safe to run again on the same move.
106
+ # Safe to run again on the same move: the intent records each child
107
+ # noted, and a run finishing it (#adopt) notes only the rest. A crash
108
+ # between a note and its record notes that child twice (better than
109
+ # none).
104
110
  # @param undo [Boolean] a failed continue moving them back: its note says so
105
111
  def apply(ids, from:, to:, state_dir:, undo: false)
106
112
  return if ids.empty?
107
113
 
108
- write_intent(to, Intent.new(from: from, ids: ids), state_dir: state_dir)
114
+ intent = Intent.new(from: from, ids: ids)
115
+ left = read_intent(to, state_dir: state_dir)
116
+ intent = intent.with(noted: left.noted & ids) if left && left.from == from && left.ids.sort == ids.sort
117
+ write_intent(to, intent, state_dir: state_dir)
109
118
  copy_cursors(ids, from: from, to: to, state_dir: state_dir)
110
119
  ids.each { |id| Session.reparent(id, to: to, from: from, state_dir: state_dir) }
111
120
  move_rings(ids, from: from, to: to, state_dir: state_dir)
112
- ids.each { |id| note_child(id, to: to, undo: undo, state_dir: state_dir) }
121
+ (ids - intent.noted).each do |id|
122
+ note_child(id, to: to, undo: undo, state_dir: state_dir)
123
+ intent = intent.with(noted: intent.noted + [id])
124
+ write_intent(to, intent, state_dir: state_dir)
125
+ end
113
126
  clear_intent(to, state_dir: state_dir)
114
127
  Log.info(:worker, undo ? "delegates_moved_back" : "delegates_moved", from: from[0, 8], to: to[0, 8], count: ids.size)
115
128
  end
@@ -143,7 +156,8 @@ module Samagotchi
143
156
  data = JSON.parse(File.read(File.join(Session.session_dir(session_id, state_dir: state_dir), INTENT_FILE)))
144
157
  return nil unless data.is_a?(Hash) && Session.valid_id?(data["from"]) && data["ids"].is_a?(Array)
145
158
 
146
- Intent.new(from: data["from"], ids: data["ids"].select { |id| Session.valid_id?(id) })
159
+ noted = data["noted"].is_a?(Array) ? data["noted"].select { |id| Session.valid_id?(id) } : []
160
+ Intent.new(from: data["from"], ids: data["ids"].select { |id| Session.valid_id?(id) }, noted: noted)
147
161
  rescue JSON::ParserError, SystemCallError
148
162
  nil
149
163
  end
@@ -151,7 +165,7 @@ module Samagotchi
151
165
  def write_intent(session_id, intent, state_dir:)
152
166
  dir = Session.session_dir(session_id, state_dir: state_dir)
153
167
  FileUtils.mkdir_p(dir)
154
- AtomicFile.write(File.join(dir, INTENT_FILE), JSON.generate({ "from" => intent.from, "ids" => intent.ids }))
168
+ AtomicFile.write(File.join(dir, INTENT_FILE), JSON.generate({ "from" => intent.from, "ids" => intent.ids, "noted" => intent.noted }))
155
169
  end
156
170
 
157
171
  def clear_intent(session_id, state_dir:)
@@ -2470,7 +2470,8 @@ module Samagotchi
2470
2470
  model_key: -> { @model_key },
2471
2471
  state_dir: -> { session_state_dir },
2472
2472
  scratch: -> { @scratch },
2473
- llm_context: -> { @session&.llm_context }
2473
+ llm_context: -> { @session&.llm_context },
2474
+ frontend: -> { interface }
2474
2475
  )
2475
2476
  end
2476
2477
 
@@ -40,7 +40,7 @@ module Samagotchi
40
40
  :system_prefix, :user_prefix, :assistant_prefix,
41
41
  :model_prefix,
42
42
  :stop_sequences, :tool_decl_format,
43
- :image_template
43
+ :image_template, :image_check_token
44
44
 
45
45
  def initialize(config)
46
46
  @name = config[:name]
@@ -65,10 +65,12 @@ module Samagotchi
65
65
  # How the chat template wraps an image's media marker ("%{marker}"),
66
66
  # or nil when chi doesn't know it yet (native images are refused).
67
67
  @image_template = config[:image_template]
68
+ # A token the server's chat template must contain for images to be
69
+ # sent (VisionSupport); defaults to the template's opening token.
70
+ @image_check_token = config[:image_check_token] || image_open_token
68
71
  end
69
72
 
70
- # The token the image template opens with, e.g. "<|vision_start|>": the
71
- # server's chat template must use it too (VisionSupport).
73
+ # The token the image template opens with, e.g. "<|vision_start|>".
72
74
  def image_open_token
73
75
  image_template&.split("%{marker}")&.first.to_s
74
76
  end
@@ -92,7 +94,12 @@ module Samagotchi
92
94
  assistant_prefix: "",
93
95
  model_prefix: "",
94
96
  stop_sequences: ["<turn|>", "<|tool_response>"],
95
- tool_decl_format: :gemma4
97
+ tool_decl_format: :gemma4,
98
+ # The bare marker: llama.cpp's mtmd wraps Gemma 4 images in
99
+ # <|image>…<image|> itself, as its chat path does (V13 spike). The
100
+ # template writes <|image|> for an image part; Gemma 3's doesn't.
101
+ image_template: "%{marker}",
102
+ image_check_token: "<|image|>"
96
103
  )
97
104
  end
98
105
 
@@ -25,9 +25,11 @@ module Samagotchi
25
25
  # model's memory overlay key (ctx.model, ctx.model_key).
26
26
  # +steer+ takes (text, label), +stop_turn+ and +stop_generation+
27
27
  # (reason, label), each true when it acted on a running turn.
28
+ # +frontend+ returns the Engine's interface (:repl, :worker,
29
+ # :non_interactive), which ctx.frontend names for plugins.
28
30
  Host = Struct.new(:session_id, :cwd, :messages, :messages_partial, :notify, :ask_user, :cancelled, :card,
29
31
  :ask_model, :model_name, :model_key, :state_dir, :scratch, :llm_context, :steer, :stop_turn, :stop_generation,
30
- keyword_init: true)
32
+ :frontend, keyword_init: true)
31
33
 
32
34
  # ctx.ask_model failed: the model couldn't be reached, timed out, or
33
35
  # sent nothing usable. The message says why, for the user.
@@ -103,6 +105,16 @@ module Samagotchi
103
105
  # Whether the session is a `chi scratch` one (deleted when it ends).
104
106
  def scratch? = !!@host.scratch&.call
105
107
 
108
+ # ctx.frontend's values, by the Engine's interface.
109
+ FRONTENDS = { repl: :repl, non_interactive: :one_shot, worker: :worker }.freeze
110
+
111
+ # What runs the session, read now (the host sets it after the plugins
112
+ # load): :repl (the REPL, -p without --non-interactive), :one_shot
113
+ # (-p --non-interactive: one turn, then exit) or :worker (a session
114
+ # worker: the web, an attached TUI). A host without one is :worker.
115
+ # @return [Symbol]
116
+ def frontend = FRONTENDS.fetch(@host.frontend&.call, :worker)
117
+
106
118
  # Whether the session is a delegate child (Session#delegate?): a task
107
119
  # another session handed over, not the user's own.
108
120
  def delegate? = !!saved_session&.delegate?
@@ -59,30 +59,45 @@ module Samagotchi
59
59
  [text + prefill_for(messages, profile, prefill), images]
60
60
  end
61
61
 
62
- def self.image_lines(items, profile, images)
63
- return "" if items.empty?
62
+ # A message's image lines: +text+ holds them all in order (what goes
63
+ # inside the message); +placeholders+ and +markers+ split the lines of
64
+ # images not sent from the sent ones' media markers, for Gemma's tool
65
+ # response, whose markers go after the block.
66
+ ImageLines = Data.define(:lines) do
67
+ def text = join(lines)
68
+ def placeholders = join(lines.reject(&:last))
69
+ def markers = join(lines.select(&:last))
70
+
71
+ private
72
+
73
+ def join(subset) = subset.empty? ? "" : "\n#{subset.map(&:first).join("\n")}"
74
+ end
64
75
 
76
+ def self.image_lines(items, profile, images)
65
77
  lines = items.each_with_index.map do |item, index|
66
- next item.placeholder unless item.sent?
67
- next ImageRef.placeholder(item.ref, ImagePlan::CANT_SEE) unless profile.image_template
78
+ next [item.placeholder, false] unless item.sent?
79
+ next [ImageRef.placeholder(item.ref, ImagePlan::CANT_SEE), false] unless profile.image_template
68
80
 
69
81
  images << item.data
70
- "[image #{index + 1}: #{ImageRef.name(item.ref)}] " \
71
- "#{Kernel.format(profile.image_template, marker: ImagePlan::NATIVE_PLACEHOLDER)}"
82
+ ["[image #{index + 1}: #{ImageRef.name(item.ref)}] " \
83
+ "#{Kernel.format(profile.image_template, marker: ImagePlan::NATIVE_PLACEHOLDER)}", true]
72
84
  end
73
- "\n#{lines.join("\n")}"
85
+ ImageLines.new(lines: lines)
74
86
  end
75
87
 
76
88
  def self.format_with_turn_markers(messages, profile, suffixes)
77
89
  last_user = messages.rindex { |m| m[:role] == "user" } || -1
78
90
  parts = messages.each_with_index.map do |m, index|
79
- content = prompt_content_for(m, profile) + suffixes[index]
91
+ lines = suffixes[index]
92
+ content = prompt_content_for(m, profile) + (m[:role] == "tool_response" ? lines.placeholders : lines.text)
80
93
  previous = index.positive? ? messages[index - 1][:role] : nil
81
94
  following = messages[index + 1]&.dig(:role)
82
95
  case m[:role]
83
96
  when "tool_response"
84
- # Inside the model's turn; closed when another role follows.
85
- tool_response_blocks(content, profile) +
97
+ # Inside the model's turn; closed when another role follows. Its
98
+ # sent images go after the blocks, outside the quoted value, as
99
+ # Gemma's chat template puts them; placeholder lines stay inside.
100
+ tool_response_blocks(content, profile) + lines.markers +
86
101
  (following && following != "tool_response" && following != "model" ? "#{profile.turn_end}\n" : "")
87
102
  when "model"
88
103
  content = strip_gemma_thought(content) if index < last_user && !content.include?(profile.tool_call_open)
@@ -136,7 +151,7 @@ module Samagotchi
136
151
  parts = []
137
152
 
138
153
  messages.each_with_index do |m, index|
139
- content = prompt_content_for(m, profile) + suffixes[index]
154
+ content = prompt_content_for(m, profile) + suffixes[index].text
140
155
  case m[:role]
141
156
  when "system"
142
157
  parts << "#{profile.system_prefix}#{content}<|im_end|>\n"
@@ -16,7 +16,10 @@ module Samagotchi
16
16
  ["[[SAMAGOTCHI_LITERAL_GEMMA_STRING_DELIM]]", '<|"|>'],
17
17
  ["[[SAMAGOTCHI_LITERAL_THINK_OPEN]]", "<|think|>"],
18
18
  ["[[SAMAGOTCHI_LITERAL_THOUGHT_CHANNEL_OPEN]]", ModelProfile::GEMMA_THOUGHT_CHANNEL_OPEN],
19
- ["[[SAMAGOTCHI_LITERAL_THOUGHT_CHANNEL_CLOSE]]", ModelProfile::GEMMA_THOUGHT_CHANNEL_CLOSE]
19
+ ["[[SAMAGOTCHI_LITERAL_THOUGHT_CHANNEL_CLOSE]]", ModelProfile::GEMMA_THOUGHT_CHANNEL_CLOSE],
20
+ ["[[SAMAGOTCHI_LITERAL_IMAGE_SOFT]]", "<|image|>"],
21
+ ["[[SAMAGOTCHI_LITERAL_IMAGE_START]]", "<|image>"],
22
+ ["[[SAMAGOTCHI_LITERAL_IMAGE_END]]", "<image|>"]
20
23
  ].freeze
21
24
 
22
25
  QWEN_TOKEN_PAIRS = [
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "question_slot"
4
4
  require_relative "../turn_flow"
5
+ require_relative "../question_desk"
5
6
 
6
7
  module Samagotchi
7
8
  class TerminalUI
@@ -80,9 +81,15 @@ module Samagotchi
80
81
  " waiting in parent #{@relayed_to} too (answering here works)" if @relayed_to
81
82
  end
82
83
 
84
+ # The line a question dismissed in a --non-interactive run leaves (no
85
+ # one could answer it there): the REPL's own, and an attached UI's on
86
+ # its cancel (QuestionDesk::UNANSWERABLE_REASON).
87
+ UNANSWERABLE_TEXT = "(dismissed: no one to answer in a non-interactive run)"
88
+
83
89
  # What a question closed with no answer here says: a relayed approval
84
90
  # names where it went; else "(question cancelled)".
85
91
  def closed_text(reason)
92
+ return UNANSWERABLE_TEXT if reason.to_s == QuestionDesk::UNANSWERABLE_REASON
86
93
  return CONTINUE_CLOSED.fetch(reason.to_s, "(question cancelled)") if continue?
87
94
  return "(question cancelled)" unless @delegate
88
95
 
@@ -1356,7 +1356,7 @@ module Samagotchi
1356
1356
  # dismissed it.
1357
1357
  def dismiss_unaskable_question(prompt)
1358
1358
  @engine.cancel_question(QuestionDesk::UNANSWERABLE_REASON) rescue nil
1359
- banner(prompt.summary("(dismissed: no one to answer in a non-interactive run)", paint: method(:paint)))
1359
+ banner(prompt.summary(QuestionPrompt::UNANSWERABLE_TEXT, paint: method(:paint)))
1360
1360
  false
1361
1361
  end
1362
1362
 
@@ -213,7 +213,7 @@ module Samagotchi
213
213
  return record unless record["status"] == "running"
214
214
 
215
215
  pid = record["pid"]
216
- return record if chis_group?(record)
216
+ return record if chis_group?(record, started: record["pid_started"])
217
217
  # Gone: its exit code says how it ended.
218
218
  return mark_finished_without_exit_code(record) if ProcessGroup.signalable?(pid) && !ProcessGroup.alive?(pid)
219
219
 
@@ -222,8 +222,9 @@ module Samagotchi
222
222
 
223
223
  # Whether the record's pid still leads its own group. With +started+
224
224
  # (the start time recorded at task_create), also the same process: a
225
- # ps per call, so only task_stop asks it, just before the signal;
226
- # a refresh (each task_wait poll, task_list) checks the group only.
225
+ # ps per call on macOS (~5 ms), asked by each refresh (task_list,
226
+ # task_get, each task_wait poll) so a reused pid reads as exited, and
227
+ # by task_stop again just before the signal.
227
228
  def chis_group?(record, started: nil) = ProcessGroup.leader?(record["pid"], started: started)
228
229
 
229
230
  # A running record whose pid isn't a group chi started (NOT_CHIS_PROCESS)
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.48.0"
4
+ VERSION = "0.49.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -73,9 +73,9 @@ module Samagotchi
73
73
  return no("the server gives no media marker (update llama.cpp)") unless media_marker(props)
74
74
  return no("profile #{profile&.name || "?"} has no image template yet") unless profile&.image_template
75
75
 
76
- open = profile.image_open_token
77
- unless open.empty? || body["chat_template"].to_s.include?(open)
78
- return no("the server's chat template doesn't use #{open} (profile #{profile.name})")
76
+ check = profile.image_check_token
77
+ unless check.empty? || body["chat_template"].to_s.include?(check)
78
+ return no("the server's chat template doesn't use #{check} (profile #{profile.name})")
79
79
  end
80
80
 
81
81
  Answer.new(value: true, reason: nil)
@@ -2265,10 +2265,15 @@ const streamHandlers = {
2265
2265
  if (view.resync) await resync();
2266
2266
  // A card's action that isn't anytime (the step-limit question's
2267
2267
  // /continue) has no bubble: nothing to remove. An anytime or queued
2268
- // one's bubble was drawn at its command_queued: filled in here.
2268
+ // one's bubble was drawn at its command_queued: filled in here. One
2269
+ // queued for after the turn ran after it: its bubble moves from among
2270
+ // the turn's rows to after its answer and timing line.
2269
2271
  const queued = view.anytime || view.queued ? commandBubble(view.commandId) : null;
2270
2272
  if (view.hidden) queued?.remove();
2271
- else if (queued) drawCommandBubble(queued, view);
2273
+ else if (queued && view.queued && !view.anytime) {
2274
+ queued.remove();
2275
+ addCommandBubble(view);
2276
+ } else if (queued) drawCommandBubble(queued, view);
2272
2277
  else addCommandBubble(view);
2273
2278
  },
2274
2279
  // An anytime command (/help, a plugin's /btw) runs at once, beside a
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.48.0
4
+ version: 0.49.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dmitry Dedov