samagotchi 0.27.0 → 0.29.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.
Files changed (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +65 -1
  3. data/docs/cli.md +6 -3
  4. data/docs/configuration.md +17 -3
  5. data/docs/internals/prompt-caching.md +38 -7
  6. data/docs/sessions.md +1 -1
  7. data/lib/samagotchi/bundle_command.rb +4 -2
  8. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  9. data/lib/samagotchi/config.rb +8 -0
  10. data/lib/samagotchi/desktop/macos/App.swift +6 -4
  11. data/lib/samagotchi/desktop/macos/ChiRunner.swift +5 -3
  12. data/lib/samagotchi/desktop/macos/Panel.swift +30 -10
  13. data/lib/samagotchi/desktop/macos.rb +5 -1
  14. data/lib/samagotchi/engine.rb +5 -4
  15. data/lib/samagotchi/guardrails/shell_lex.rb +79 -5
  16. data/lib/samagotchi/kernel_loop.rb +8 -1
  17. data/lib/samagotchi/llm/openai_chat.rb +40 -4
  18. data/lib/samagotchi/llm/prompt_cache.rb +31 -5
  19. data/lib/samagotchi/memory_bundle/installer.rb +14 -0
  20. data/lib/samagotchi/session.rb +9 -0
  21. data/lib/samagotchi/session_commands.rb +6 -2
  22. data/lib/samagotchi/session_manager.rb +4 -3
  23. data/lib/samagotchi/sessions_command.rb +26 -13
  24. data/lib/samagotchi/terminal_ui/repl_input.rb +13 -0
  25. data/lib/samagotchi/terminal_ui.rb +5 -0
  26. data/lib/samagotchi/tool_activity.rb +32 -6
  27. data/lib/samagotchi/tools/builtins.rb +10 -7
  28. data/lib/samagotchi/tools/task_runtime.rb +21 -0
  29. data/lib/samagotchi/turn_note.rb +11 -1
  30. data/lib/samagotchi/version.rb +1 -1
  31. data/lib/samagotchi/vision_context.rb +17 -4
  32. data/lib/samagotchi/web/public/app.js +14 -4
  33. data/lib/samagotchi/web/public/index.html +37 -19
  34. data/lib/samagotchi/web/public/sessions_list.js +21 -4
  35. data/lib/samagotchi/web/public/stage_model.js +5 -2
  36. data/lib/samagotchi/web/public/task_stop.js +24 -1
  37. data/lib/samagotchi/web/public/turn_model.js +14 -5
  38. data/lib/samagotchi/web/public/turn_view.js +46 -10
  39. data/lib/samagotchi/worker.rb +9 -0
  40. metadata +1 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b91f830918a3f58dac1d54820450ec90b4caa2d8f970b3fab03c8a0199b3ac2e
4
- data.tar.gz: 1d1f0f1dc839247801be1462a895e8a57e189a68882fbaeb5a7707fdb4add0ab
3
+ metadata.gz: 581b7b0fa7184fb49a83588921656f2f91f05ae04538592e69874ba1207b686c
4
+ data.tar.gz: 4c381eb155ab69b933cda29461a02b111910adfb53309bb38ffc5819dfc764d6
5
5
  SHA512:
6
- metadata.gz: 398faa2152be479cf78093fb9c752158932a2c186bf1fa5fd1ee9a622895bf742f82f1a25c843febfb877c826cee869623ee9871c50154015fdb54d02a490054
7
- data.tar.gz: 35a4b45af554dd9cfd79c87d67ed7d819d14759421f8f669ac769ddbb1b37a64f5b0c79101f15a002ebdb4a2e2e9bee1def9eead820d50f61312c9f4a8cc41c8
6
+ metadata.gz: 84b0ba1d65c4c5d41fcbee9e925934f6fd6ee1eb4b46bb35af98b46cde28f9ad334ab56ff44e1ee503f0f7f9dab107d03429c145c7097fa35f90aa8ab86f1f4f
7
+ data.tar.gz: 7725dc03f4d5c9d42e7a5c4cae0ba5729740a6d95d37fb04c7bdcc611489907b039ad2ec9b0770c7f47ff04fc681d750309988825896c0e90c1e5b7c0dda3605
data/CHANGELOG.md CHANGED
@@ -8,6 +8,68 @@ and commands may change between minor versions. How releases are made:
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.29.0] - 2026-10-05
12
+
13
+ ### Added
14
+
15
+ - Web: a session card shows `looped` when loop-guard stopped its last turn (`stopped by <name>` for another hook),
16
+ like `chi sessions list`'s `[looped]`; the all-sessions search finds them by those words.
17
+ - `chi bundle install` warns when a bundle needs a newer chi and its guardrail rules won't load (it already warned
18
+ about its hooks and plugin).
19
+
20
+ ### Changed
21
+
22
+ - Web: a tool row shows its status as a mark (✓, ✕, ■, a spinner while it runs) instead of the word, so its command,
23
+ output and diff start right under the tool name; error, stopped and blocked calls keep their word after the title.
24
+ An open step's body sits indented under its summary.
25
+ - Web: a step with a failed call says so in its collapsed label, `3 tool calls (1 failed)`, with a red chevron; the
26
+ turn's summary counts failed calls below 3 calls too.
27
+ - Web: a `task_wait`, `task_get` or `task_stop` row names its task by the task's command instead of its id, a wait with
28
+ how long it waits (`bundle exec rspec · up to 600s`), also for a task started in an earlier turn; the id line stays
29
+ on hover.
30
+
31
+ ### Fixed
32
+
33
+ - Guardrails: `> /tmp/x cat <<EOF` (a redirection written with a space before the command) is read as a heredoc of
34
+ data like `cat > /tmp/x <<EOF`, and a `)` inside quotes or a heredoc body no longer ends a `$(…)` early.
35
+ - `!cmd` no longer hands a `--model` worker's model to a chi it runs as the default model.
36
+ - A session worker survives a failed save at the end of a turn (it logs it) instead of crashing.
37
+ - A turn that ends with an empty answer removes only its own retry note, not an earlier turn's cancel or failure note.
38
+ - Web: streamed chunks from llama.cpp no longer carry its whole echoed prompt to every web client.
39
+
40
+ ## [0.28.0] - 2026-10-04
41
+
42
+ ### Added
43
+
44
+ - Desktop: the panel's footer says where its text and images came from, "from clipboard" (the hotkey) or "from
45
+ selection" (Send to chi); run `chi desktop upgrade`.
46
+ - `cache.ttl: 1h` keeps a Claude model's prompt-cache breakpoints for an hour instead of 5 minutes (a write costs 2×
47
+ the input price instead of 1.25×; off by default), and `cache.key: session` sends the session id as
48
+ `prompt_cache_key` to OpenAI's API and OpenRouter (off by default).
49
+ - `chi sessions list` marks a session whose last turn loop-guard stopped with `[looped]` (another hook:
50
+ `[stopped by <name>]`); `--format json` carries `stopped_by`.
51
+
52
+ ### Changed
53
+
54
+ - Past `image.max_per_request` images, the oldest are left out in batches of half the limit instead of one per new
55
+ image, so the earlier conversation stays a cacheable prefix; the placeholder reads "an older image (chi sends up
56
+ to the newest N)".
57
+ - After loop-guard cuts a runaway reply, chi's retry note tells the model to continue the task with its next tool
58
+ call (or answer if it's done) instead of "answer briefly", which made models wrap up in the middle of a task.
59
+
60
+ ### Fixed
61
+
62
+ - REPL: a line typed ahead during a turn no longer starts a turn-end warm-up that the next turn throws away.
63
+ - Web: when one of a task's stop buttons is clicked, the other one (the stage's step list) disables too.
64
+ - Desktop: `chi desktop install` starts the helper with a bare env, so `SAMAGOTCHI_*` settings (and anything else)
65
+ from the install shell no longer stick to the helper and the chi it runs until a relaunch; run `chi desktop upgrade`.
66
+ - Desktop: ⌘⏎ on the panel's "New session" row says "A note needs a session" instead of only beeping, and the Note
67
+ button is off on that row; run `chi desktop upgrade`.
68
+ - Desktop: the panel lists live sessions in the order they started, so ⌘1…⌘9 no longer shift when a session runs a
69
+ turn (a new session comes last); run `chi desktop upgrade`.
70
+
71
+ Update with `chi update`, then `chi desktop upgrade` if you use the desktop helper.
72
+
11
73
  ## [0.27.0] - 2026-10-04
12
74
 
13
75
  ### Added
@@ -1438,7 +1500,9 @@ and long-lived sessions.
1438
1500
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
1439
1501
  hotkey panel that send selected text or the clipboard to your sessions.
1440
1502
 
1441
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.27.0...HEAD
1503
+ [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.29.0...HEAD
1504
+ [0.29.0]: https://github.com/dm1try/samagotchi/compare/v0.28.0...v0.29.0
1505
+ [0.28.0]: https://github.com/dm1try/samagotchi/compare/v0.27.0...v0.28.0
1442
1506
  [0.27.0]: https://github.com/dm1try/samagotchi/compare/v0.26.0...v0.27.0
1443
1507
  [0.26.0]: https://github.com/dm1try/samagotchi/compare/v0.25.0...v0.26.0
1444
1508
  [0.25.0]: https://github.com/dm1try/samagotchi/compare/v0.24.0...v0.25.0
data/docs/cli.md CHANGED
@@ -495,9 +495,12 @@ A model that can see images gets them these ways:
495
495
  Images are downscaled to a 1568 px long side (with `sips` on macOS or
496
496
  ImageMagick; without either, a larger image is refused with a hint) and stored
497
497
  next to the session in `<session>/images/`, and the session file keeps small
498
- references to them. Each request sends the newest 20 images of the conversation;
499
- older ones become a line like `[image shot.png 1280×800 not sent: only the
500
- newest 20 images are sent]`.
498
+ references to them. Each request sends up to the newest 20 images of the
499
+ conversation (`image.max_per_request`); past that the oldest are left out ten at
500
+ a time (half the limit), so the earlier conversation stays the same between
501
+ requests and the server's prompt cache keeps it. A left-out image becomes a line
502
+ like `[image shot.png 1280×800 not sent: an older image (chi sends up to the
503
+ newest 20)]`.
501
504
 
502
505
  A model that can't see images (a text-only model, llama.cpp without
503
506
  `--mmproj`, an mlx host) refuses a turn with images before sending it:
@@ -519,8 +519,20 @@ OpenAI-compatible host get two prompt-cache breakpoints (`cache_control` on the
519
519
  message), so each step reads the earlier prompt from Anthropic's cache instead of paying for it again. The system
520
520
  prompt goes as two text parts, the breakpoint after the first: everything sessions share, then the model, working
521
521
  directory and session lines, so a new session reads the shared part from the cache as well; the debug
522
- log's line shows `cache=on`. Nothing to configure. A provider behind a gateway may still not cache: check the
523
- cached tokens in `/stats`. Each request's own counts are in the debug log's `generation_completed` line:
522
+ log's line shows `cache=on`. A provider behind a gateway may still not cache: check the cached tokens in `/stats`.
523
+
524
+ Anthropic drops a cache entry 5 minutes after its last read, so a session you come back to after a longer pause
525
+ writes its prompt again. `cache.ttl: 1h` keeps the breakpoints an hour (the log shows `cache=1h`); a write then
526
+ costs 2× the input price instead of 1.25×, so it pays off when you often pause 5–60 minutes between turns.
527
+ `cache.key: session` sends the session id as `prompt_cache_key` (OpenAI's API and OpenRouter only; the log shows
528
+ `cache_by=session`), which OpenAI uses to route a conversation to the machine that holds its cache:
529
+
530
+ ```yaml
531
+ cache:
532
+ ttl: 1h # 5m (default) or 1h
533
+ key: session # off (default) or session
534
+ ```
535
+ Each request's own counts are in the debug log's `generation_completed` line:
524
536
  `prompt=` (its prompt tokens), `cached=` (read from the server's cache) and `cache_write=` (written to it, when the
525
537
  server reports writes); recap and side requests log theirs as `recap request_usage`.
526
538
 
@@ -784,7 +796,7 @@ downscaled first; three settings bound them (env `SAMAGOTCHI_IMAGE_*` or
784
796
  image:
785
797
  max_side: 1568 # long side in px (Claude's standard; ~1.3k tokens for 1280×800)
786
798
  max_bytes: 3750000 # larger after downscaling → re-encoded as JPEG
787
- max_per_request: 20 # older images in the conversation become placeholder lines
799
+ max_per_request: 20 # older images become placeholder lines, dropped in batches of half this
788
800
  ```
789
801
 
790
802
  Whether a model can see images is found out before a turn with images is sent:
@@ -899,6 +911,8 @@ described in their own sections.
899
911
  | `hosts.<name>.remote` | by address | | `true`/`false`: treat the host as a remote provider or a local server. See "Remote or local". |
900
912
  | `max_tool_output_chars` | `10000` | yes | Tool output kept in the conversation; a top-level key (see below). |
901
913
  | `cache.warmup` | `auto` | | `auto`: after a turn, send the next turn's prompt (up to the next message) to a local llama.cpp host on the native loop, so the next turn prefills only its message; never a remote or `api: openai` host. `off`: never. See [prompt caching](internals/prompt-caching.md#the-turn-end-warm-up). |
914
+ | `cache.ttl` | `5m` | | How long Anthropic keeps the prompt-cache breakpoints of a Claude model on a remote host: `5m` (Anthropic's default) or `1h`. A 1h cache write costs 2× the input price (5m: 1.25×), a read the same 0.1×. See "Remote or local". |
915
+ | `cache.key` | `off` | | `session`: send the session id as `prompt_cache_key` to OpenAI's API and OpenRouter, which route and cache by it; no other host gets it. `off`: none. |
902
916
  | `retry.max` | `5` | yes | See "Llama Network Retry Behavior". |
903
917
  | `retry.base_delay` | `0.5` | yes | |
904
918
  | `retry.max_delay` | `8.0` | yes | |
@@ -43,9 +43,9 @@ right-hand column happens.
43
43
  shared by every turn of this session ─────────────────────────────────────
44
44
  ┌──────────────────────────────────────────────────────────────────────────┐
45
45
  │ history user / assistant / tool messages, APPEND-ONLY │ !rollback, a failed or
46
- │ (images: the newest N, ImagePlan) │ cancelled turn's tail,
47
- │ ◄── remote Claude: breakpoint #2 on the last │ the image window
48
- │ non-system message │ sliding, history
46
+ │ (images: up to the newest N, cut in batches; ImagePlan) │ cancelled turn's tail,
47
+ │ ◄── remote Claude: breakpoint #2 on the last │ the image cut moving
48
+ │ non-system message │ a batch, history
49
49
  ├──────────────────────────────────────────────────────────────────────────┤ sanitizing (thinking
50
50
  │ tail notes reminders, turn notes, steers (system/user messages) │ stripped per spec)
51
51
  │ new prompt this turn's user message │
@@ -83,7 +83,39 @@ user message starts (`KernelLoop#warmup_prompt`) and sends it in a thread (`Clie
83
83
  server has since cleared skips its prompt cache and prefills everything (measured 0.5 s → 12 s). For the same
84
84
  reason `id_slot` is a reserved sampling key.
85
85
  - What breaks it (the warm-up simply misses): a system-prompt rebuild (`/thinking`, `/model`, a tool change),
86
- the image window sliding, `!rollback`.
86
+ the image cut moving a batch, `!rollback`.
87
+
88
+ ## The image window
89
+
90
+ A request sends at most `image.max_per_request` images (20 by default); older ones become placeholder lines
91
+ (`[image a.png 1280×800 not sent: an older image (chi sends up to the newest 20)]`). If the window slid by one
92
+ image per new image, every new image would turn the oldest sent one into a placeholder and rewrite history from
93
+ there. So the cut is a pure function of the image count (`ImagePlan.dropped_count`): nothing is dropped up to
94
+ the limit, then the oldest in whole steps of half the limit (21–30 images drop 10, 31–40 drop 20). Between two
95
+ step boundaries the earlier messages stay byte-identical; at a boundary the history from the newly cut image on
96
+ is prefilled once. The native and the chat loop use the same plan.
97
+
98
+ ## Remote caches: TTL and routing
99
+
100
+ - **TTL.** Anthropic keeps a breakpoint 5 minutes after its last read; a session the user comes back to later
101
+ writes its prompt again. `cache.ttl: 1h` sends `cache_control: {type: "ephemeral", ttl: "1h"}` on both
102
+ breakpoints (the log line shows `cache=1h`). Off by default: a 1h write costs 2× the input price, a 5m write
103
+ 1.25×, a read 0.1× either way, so 1h pays off only when pauses of 5–60 minutes are common.
104
+ - **Routing.** Every chat request carries a `Session-Id` header, which OpenRouter uses to keep a conversation on
105
+ one provider. `cache.key: session` also sends the session id as `prompt_cache_key` in the body, the field
106
+ OpenAI's API routes and caches by (OpenRouter honours it too); the log line shows `cache_by=session`. Only
107
+ `api.openai.com` and OpenRouter get it, and only the session's own chat requests (not recap or `/btw`): a local
108
+ llama.cpp, Splash or another gateway may reject an unknown field. Off by default.
109
+
110
+ ## Reading the numbers
111
+
112
+ - The debug log's `generation_completed` line: `prompt=` (the request's prompt tokens), `cached=` (read from the
113
+ server's cache) and `cache_write=` (written to it, where the provider reports writes). The `http` line of a
114
+ remote Claude request shows `cache=on` (or `cache=1h`) when it carried breakpoints.
115
+ - The warm-up logs `model warmup` with `cached=`, `prefilled=` and `prefill_ms=`.
116
+ - `/stats`: "cached N (P%)" and "cache writes" for the session.
117
+ - A healthy session: from the second request on `cached=` is close to `prompt=`; a second fresh session in the
118
+ same project reads everything up to the volatile tail.
87
119
 
88
120
  ## Rules for changes
89
121
 
@@ -114,7 +146,6 @@ user message starts (`KernelLoop#warmup_prompt`) and sends it in a thread (`Clie
114
146
  a slot (`id_slot`) is the hazard. With `--cache-ram 0` or an old single-slot build, a recap does evict the
115
147
  session. `--ctx-checkpoints` controls how many restore points a hybrid model keeps. chi sends
116
148
  `cache_prompt: true` on every native request.
117
- - **OpenRouter / Anthropic:** the default cache TTL is 5 minutes. Provider routing (which upstream serves a
118
- request) also decides whether a cache is there to hit.
149
+ - **OpenRouter / Anthropic:** the default cache TTL is 5 minutes (`cache.ttl: 1h` for an hour, see above).
150
+ Provider routing (which upstream serves a request) also decides whether a cache is there to hit.
119
151
 
120
- Still to come: image-window batches and longer remote TTLs.
data/docs/sessions.md CHANGED
@@ -56,7 +56,7 @@ chi sessions clean --dry-run --days 7 # test sessions older than 7 da
56
56
 
57
57
  `--dry-run` is the safe preview. `--keep N` keeps the N newest sessions that stay: one that goes anyway (a leftover scratch session, one left empty, one older than `--days`) takes no place in the count. Web has no prune endpoint; use the CLI.
58
58
 
59
- `chi sessions list` shows each session's saved recap, its first sentence without the "The user was…" opening (as on the web cards), in place of its last prompt, cut to 60 characters; a session with no recap shows its last prompt. A delegated session's row ends with `↳ <parent's short id>` (plain and `--live`; `--format json` has `parent_id`); rows keep their `updated_at` order, so a parent may be on another page than its children. After the status, `ctx 12%` says how full the context was after the session's last counted turn (from its `analytics.json`; blank when no turn had a server count or the window is unknown; `ctx_pct` in `--format json`). The web's session cards show it quietly too (`12%`), and a session's ctx meter shows it on load, before its next turn streams.
59
+ `chi sessions list` shows each session's saved recap, its first sentence without the "The user was…" opening (as on the web cards), in place of its last prompt, cut to 60 characters; a session with no recap shows its last prompt. A session whose last turn a hook stopped carries `[looped]` when the hook was loop-guard (the thinking watch's cut, or its stop) and `[stopped by <hook>]` for any other hook, after `[archived]` (`--format json` has it as `stopped_by`; from `Session#last_turn`, so it stays until a later turn ends differently). The web's session cards wear the same marker as a badge: `looped` or `stopped by <hook>` after the status dot (a session that also waits on you shows only its waiting badge: the stop is behind the need), and the all-view's search matches its words too. A delegated session's row ends with `↳ <parent's short id>` (plain and `--live`; `--format json` has `parent_id`); rows keep their `updated_at` order, so a parent may be on another page than its children. After the status, `ctx 12%` says how full the context was after the session's last counted turn (from its `analytics.json`; blank when no turn had a server count or the window is unknown; `ctx_pct` in `--format json`). The web's session cards show it quietly too (`12%`), and a session's ctx meter shows it on load, before its next turn streams.
60
60
 
61
61
  **Projects:** a session belongs to the git project it was started in: the repository, whichever worktree or subfolder of it (the same project root memories use). `chi sessions list` (with `--live` and `--format` too) and `chi web` show the current folder's project; `--scope=all` shows every session, and so does a folder in no repo (`~`). `--cwd PATH` is a folder filter instead of the project. The project is stored with the session (`project_root` in its JSON, `project` in `--format json`), so a session keeps it after its worktree is deleted; sessions older than that are placed by their folder, and one whose folder is gone shows in `--scope=all` only. Retention, `--resume`/`--attach ID`, `chi send`/`chi note ID` and `chi note --all` (every live session) are not scoped. The agent's `list_sessions` lists its own project's sessions; `cwd: "/"` lists every one.
62
62
 
@@ -36,7 +36,8 @@ module Samagotchi
36
36
  build [--scope system|project] [--name NAME] [--version VER] [--description DESC] [--out PATH] [FILES...]
37
37
  Build local memories and installed hooks (and plugin) into a shareable bundle (dir or zip).
38
38
  --scope selects source dir (default: system). --out inferred from extension; default <name>.zip.
39
- FILES... optional allowlist of *.md basenames to include (default: all but installed bundles' ones).
39
+ FILES... optional allowlist of *.md basenames to include (default: all but installed bundles' ones);
40
+ a named memory brings its model overlays (<name>.<model-key>.md).
40
41
 
41
42
  trash [--empty] [--dry-run] [--older-than DAYS]
42
43
  List bundle trash (moved files from uninstalls/upgrades).
@@ -61,7 +62,8 @@ module Samagotchi
61
62
  build [--scope system|project] [--name NAME] [--version VER] [--description DESC] [--out PATH] [FILES...]
62
63
  Build local memories and installed hooks into a shareable bundle (dir or zip).
63
64
  --scope selects source dir (default: system). --out inferred from extension; default <name>.zip.
64
- FILES... optional allowlist of *.md basenames to include (default: all but installed bundles' ones).
65
+ FILES... optional allowlist of *.md basenames to include (default: all but installed bundles' ones);
66
+ a named memory brings its model overlays (<name>.<model-key>.md).
65
67
 
66
68
  Examples:
67
69
  chi bundle build --scope system
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.27.0
3
+ version: 0.29.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:
@@ -142,6 +142,14 @@ module Samagotchi
142
142
  # prompt on a local llama.cpp host while the user reads; off never
143
143
  # does. A :string, since YAML reads an unquoted off as false.
144
144
  Entry.new(key: "cache.warmup", yaml_path: %w[cache warmup], type: :string, default: "auto", expose: %i[env config]),
145
+ # How long Anthropic keeps a cache breakpoint (PromptCache): 5m, or
146
+ # 1h for long reading gaps (a 1h write costs 2x the input price, a 5m
147
+ # one 1.25x, so it's opt-in).
148
+ Entry.new(key: "cache.ttl", yaml_path: %w[cache ttl], type: :string, default: "5m", expose: %i[env config]),
149
+ # session sends the session id as `prompt_cache_key` to OpenAI's API
150
+ # and OpenRouter (OpenAIChat), which route and cache by it; off sends
151
+ # none. A :string, since YAML reads an unquoted off as false.
152
+ Entry.new(key: "cache.key", yaml_path: %w[cache key], type: :string, default: "off", expose: %i[env config]),
145
153
 
146
154
  Entry.new(key: "retry.max", yaml_path: %w[retry max], type: :integer, default: 5, expose: %i[env config cli]),
147
155
  Entry.new(key: "retry.base_delay", yaml_path: %w[retry base_delay], type: :float, default: 0.5, expose: %i[env config cli]),
@@ -18,7 +18,7 @@ final class ServiceProvider: NSObject {
18
18
  error.pointee = "No text or image in the selection" as NSString
19
19
  return
20
20
  }
21
- app?.open(text: text, images: images)
21
+ app?.open(text: text, images: images, origin: "selection")
22
22
  }
23
23
  }
24
24
 
@@ -60,12 +60,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
60
60
  /// The hotkey doesn't activate us, so the frontmost app is the source.
61
61
  func openFromClipboard() {
62
62
  let (text, images) = ImageIntake.read(NSPasteboard.general)
63
- open(text: text, images: images)
63
+ open(text: text, images: images, origin: "clipboard")
64
64
  }
65
65
 
66
- func open(text: String, images: [PanelImage] = []) {
66
+ /// @param origin "clipboard" (the hotkey) or "selection" (the Service)
67
+ func open(text: String, images: [PanelImage] = [], origin: String) {
67
68
  let from = sourceApp
68
- panel.show(text: text, images: images, source: from?.localizedName?.lowercased() ?? "desktop", returnTo: from)
69
+ panel.show(text: text, images: images, origin: origin, source: from?.localizedName?.lowercased() ?? "desktop",
70
+ returnTo: from)
69
71
  }
70
72
  }
71
73
 
@@ -118,11 +118,13 @@ final class ChiRunner {
118
118
  stdin: stdin, timeout: timeout ?? self.timeout, completion: completion)
119
119
  }
120
120
 
121
- /// The live sessions, then up to +recentCount+ stopped ones, newest
122
- /// first. A session a chi REPL holds is in neither: it takes no notes or
121
+ /// The live sessions, oldest started first, then up to +recentCount+
122
+ /// stopped ones, newest first. The live order is by creation so ⌘1…⌘9
123
+ /// stay on their sessions as turns update them; a new one comes last.
124
+ /// A session a chi REPL holds is in neither: it takes no notes or
123
125
  /// messages. A failed second call just leaves "recent" empty.
124
126
  func sessions(recentCount: Int = 3, completion: @escaping (Result<[LiveSession], ChiError>) -> Void) {
125
- list(["--live"]) { result in
127
+ list(["--live", "--sort", "created_at", "--order", "asc"]) { result in
126
128
  guard case .success(let live) = result else { completion(result); return }
127
129
  self.list(["--limit", "20"]) { recent in
128
130
  let liveIds = Set(live.map(\.id))
@@ -20,6 +20,9 @@ final class PanelModel: ObservableObject {
20
20
  /// The selection or clipboard: the quoted context of a message, or a note.
21
21
  @Published var text = ""
22
22
  @Published var source = ""
23
+ /// The path the opening text and images took: "clipboard" (the hotkey)
24
+ /// or "selection" (the Service); "" when the panel opened empty.
25
+ @Published var origin = ""
23
26
  /// Sent as `--image` with a message; notes are text only.
24
27
  @Published var images: [PanelImage] = []
25
28
  /// The thumbnail under the pointer (shows its ✕). Kept here, not in a
@@ -74,8 +77,9 @@ final class PanelModel: ObservableObject {
74
77
  }
75
78
  var live: [LiveSession] { sessions.filter { !$0.recent } }
76
79
 
77
- /// One list for rows, ⌘ numbers and selection: live sessions, then kitty
78
- /// windows, then recent sessions.
80
+ /// One list for rows, ⌘ numbers and selection: live sessions (oldest
81
+ /// started first: their numbers stay put), then kitty windows, then
82
+ /// recent sessions.
79
83
  var targets: [Target] { live.map(Target.chi) + kittyWindows.map(Target.kitty) + recent.map(Target.chi) }
80
84
 
81
85
  /// Up to maxImages; the rest is dropped (and its temp files deleted).
@@ -534,9 +538,17 @@ struct PanelView: View {
534
538
  .padding(.horizontal, 8).padding(.vertical, 4)
535
539
  .background(Capsule().fill(Color.primary.opacity(0.07)))
536
540
 
537
- Text(byteLabel)
538
- .font(.system(size: 11).monospacedDigit())
539
- .foregroundColor(model.bytes > noteCap ? .red : .secondary)
541
+ HStack(spacing: 0) {
542
+ if !model.origin.isEmpty {
543
+ Text("from \(model.origin) · ").foregroundColor(.secondary)
544
+ .help(model.origin == "clipboard" ? "opened with the hotkey: the text and images are the clipboard's"
545
+ : "opened with Send to chi: the text and images are the selection")
546
+ }
547
+ Text(byteLabel).foregroundColor(model.bytes > noteCap ? .red : .secondary)
548
+ }
549
+ .font(.system(size: 11).monospacedDigit())
550
+ .lineLimit(1)
551
+ .fixedSize()
540
552
 
541
553
  Text(model.message)
542
554
  .font(.system(size: 11))
@@ -554,8 +566,9 @@ struct PanelView: View {
554
566
  .help("paste it into the agent's input without Enter: add more, then press Enter there")
555
567
  } else {
556
568
  Button("Note ⌘⏎") { send(.note) }
557
- .disabled(!model.sendEnabled || !model.selectedKitty.isEmpty)
558
- .help("add it as background the model sees on its next turn; starts no turn")
569
+ .disabled(!model.sendEnabled || !model.selectedKitty.isEmpty || model.newSelected)
570
+ .help(model.newSelected ? "a note needs a session: pick one, or ⏎ starts a new one with the message"
571
+ : "add it as background the model sees on its next turn; starts no turn")
559
572
  }
560
573
  Button(action: { send(.message) }) {
561
574
  if model.phase == .sending { ProgressView().controlSize(.small) } else { Text("Send ⏎") }
@@ -753,8 +766,9 @@ final class PanelController: NSObject, NSWindowDelegate {
753
766
  return true
754
767
  }
755
768
 
769
+ /// @param origin "clipboard" or "selection": where text and images came from
756
770
  /// @param returnTo the app to give focus back to on close
757
- func show(text: String, images: [PanelImage] = [], source: String, returnTo app: NSRunningApplication?) {
771
+ func show(text: String, images: [PanelImage] = [], origin: String, source: String, returnTo app: NSRunningApplication?) {
758
772
  returnTo = app
759
773
  // A show on an open panel resets it without a close.
760
774
  dropImages()
@@ -762,6 +776,7 @@ final class PanelController: NSObject, NSWindowDelegate {
762
776
  model.images = []
763
777
  model.add(images)
764
778
  model.text = text
779
+ model.origin = text.isEmpty && images.isEmpty ? "" : origin
765
780
  model.source = source
766
781
  model.message = ""
767
782
  model.newSelected = false
@@ -873,13 +888,18 @@ final class PanelController: NSObject, NSWindowDelegate {
873
888
  model.message = "Paste only is for kitty windows"
874
889
  return
875
890
  }
891
+ // A note into a session that doesn't exist yet makes no sense.
892
+ if kind == .note, new {
893
+ NSSound.beep()
894
+ model.message = "A note needs a session"
895
+ return
896
+ }
876
897
  if kind == .note, !model.images.isEmpty {
877
898
  NSSound.beep()
878
899
  model.message = "Notes are text only: ⏎ sends the image as a message"
879
900
  return
880
901
  }
881
- // A note into a session that doesn't exist yet makes no sense.
882
- guard model.sendEnabled, new ? kind == .message : !(ids.isEmpty && windows.isEmpty) else { NSSound.beep(); return }
902
+ guard model.sendEnabled, new || !(ids.isEmpty && windows.isEmpty) else { NSSound.beep(); return }
883
903
  model.phase = .sending
884
904
  model.message = ""
885
905
  if !new {
@@ -310,7 +310,11 @@ module Samagotchi
310
310
  # type may otherwise show only after a re-login).
311
311
  @runner.run([LSREGISTER, "-f", app_path])
312
312
  @runner.run([PBS, "-update"])
313
- @runner.run(["open", "-g", app_path])
313
+ # open hands the app its own env, so the install shell's
314
+ # (SAMAGOTCHI_* knobs, tokens) would stay in the helper and in every
315
+ # chi it runs until a relaunch. Through env -i the app gets launchd's
316
+ # bare env, as at login; launch.json carries what chi needs.
317
+ @runner.run(["/usr/bin/env", "-i", "HOME=#{@env["HOME"] || Dir.home}", "/usr/bin/open", "-g", app_path])
314
318
  end
315
319
 
316
320
  def quit
@@ -1780,7 +1780,7 @@ module Samagotchi
1780
1780
  # A caller's check that the next turn starts at once (input queued for
1781
1781
  # it: a worker's inbox) or that none follows (a one-shot run): no
1782
1782
  # warm-up then. nil: neither.
1783
- attr_writer :next_turn_waiting
1783
+ attr_accessor :next_turn_waiting
1784
1784
 
1785
1785
  # After a completed turn, prefill the next turn's prompt up to its user
1786
1786
  # message while the user reads (PromptWarmup, cache.warmup). Only on a
@@ -1942,11 +1942,12 @@ module Samagotchi
1942
1942
  # that way: the note, and nothing made up as its answer. The note's
1943
1943
  # marker is for the UIs (the notice, and the empty steps after a
1944
1944
  # reload); it goes on the result's conversation too (the REPL keeps it).
1945
- # A retry's nudge at the tail goes: this note says it all.
1945
+ # A retry's nudge at the tail goes: this note says it all. An earlier
1946
+ # turn's note stays: it says why that turn ended.
1946
1947
  if result.empty_answer?
1947
1948
  note = TurnNote.empty(retries: result.empty_retries, steps: result.empty_steps)
1948
- conversation&.replace(TurnNote.without_trailing(conversation))
1949
- saved = TurnNote.without_trailing(conversation || turn.session.messages)
1949
+ conversation&.replace(TurnNote.without_trailing_nudge(conversation))
1950
+ saved = TurnNote.without_trailing_nudge(conversation || turn.session.messages)
1950
1951
  conversation << note if conversation
1951
1952
  saved + [note]
1952
1953
  elsif result.canceled? && conversation
@@ -169,19 +169,76 @@ module Samagotchi
169
169
  add(SUBST, close + 1 - @i)
170
170
  end
171
171
 
172
+ # From $( to the ) that closes it, as one SUBST. A quote or a
173
+ # heredoc body inside it is skipped over: a ) in one of those
174
+ # doesn't close the substitution.
172
175
  def substitution
173
176
  depth = 0
174
177
  j = @i + 1
175
178
  loop do
176
- depth += 1 if @s[j] == "("
177
- depth -= 1 if @s[j] == ")"
178
- j += 1
179
- break if depth.zero? || j >= @s.size
179
+ break if j >= @s.size
180
+
181
+ c = @s[j]
182
+ if ["'", '"'].include?(c)
183
+ j = quote_end(j)
184
+ elsif c == "("
185
+ depth += 1
186
+ j += 1
187
+ elsif c == ")"
188
+ depth -= 1
189
+ j += 1
190
+ break if depth.zero?
191
+ elsif @s[j, 2] == "<<"
192
+ j = substitution_heredoc(j)
193
+ else
194
+ j += 1
195
+ end
180
196
  end
181
197
  @unterminated = true unless depth.zero?
182
198
  add(SUBST, j - @i)
183
199
  end
184
200
 
201
+ # The index after the quote starting at +j+, a backslash in a double
202
+ # quote escaping the next character; the text's end when it is never
203
+ # closed.
204
+ def quote_end(j)
205
+ quote = @s[j]
206
+ k = j + 1
207
+ while k < @s.size
208
+ if quote == '"' && @s[k] == "\\" then k += 2
209
+ elsif @s[k] == quote then return k + 1
210
+ else k += 1
211
+ end
212
+ end
213
+ k
214
+ end
215
+
216
+ # From a << at +j+ inside a $(…) past its body's terminator line
217
+ # (nothing is lexed: the body is only stepped over), or on to the
218
+ # next character when no tag follows or the terminator never comes
219
+ # (a << that is no heredoc, as arithmetic's 1<<3, stays scanned).
220
+ def substitution_heredoc(j)
221
+ dash = @s[j + 2] == "-"
222
+ k = j + (dash ? 3 : 2)
223
+ k += 1 while [" ", "\t"].include?(@s[k])
224
+ tag, _quoted, stop = heredoc_tag(k)
225
+ return j + 1 if tag.empty?
226
+
227
+ eol = @s.index("\n", stop)
228
+ return j + 1 if eol.nil?
229
+
230
+ k = eol + 1
231
+ while k < @s.size
232
+ eol = @s.index("\n", k) || @s.size
233
+ line = @s[k...eol]
234
+ line = line.sub(/\A\t+/, "") if dash
235
+ return [eol + 1, @s.size].min if line == tag
236
+
237
+ k = eol + 1
238
+ end
239
+ j + 1
240
+ end
241
+
185
242
  def comment
186
243
  @i = @s.index("\n", @i) || @s.size
187
244
  end
@@ -306,10 +363,27 @@ module Samagotchi
306
363
  def data_sink?(at)
307
364
  start = at
308
365
  start -= 1 while start.positive? && @tokens[start - 1][0] == :word
309
- verb = @tokens[start...at].map { |t| t[1] }.find { |w| !w.match?(/\A[A-Za-z_]\w*=/) && !w.match?(REDIRECT) }
366
+ verb = command_word(@tokens[start...at])
310
367
  next_op = @tokens[at..].find { |t| t[0] == :op }
311
368
  DATA_SINKS.include?(File.basename(verb.to_s)) && !["|", "|&"].include?(next_op&.dig(1))
312
369
  end
370
+
371
+ # The command word among the words before a heredoc's: the NAME=
372
+ # words and the redirections dropped, and with a redirection written
373
+ # with a space (> /tmp/x) its target word too.
374
+ def command_word(words)
375
+ i = 0
376
+ while i < words.size
377
+ word = words[i][1]
378
+ if word.match?(REDIRECT)
379
+ i += 1 if word.match?(/\A\d*[<>]{1,2}\z/)
380
+ elsif !word.match?(/\A[A-Za-z_]\w*=/)
381
+ return word
382
+ end
383
+ i += 1
384
+ end
385
+ nil
386
+ end
313
387
  end
314
388
  end
315
389
  end
@@ -372,13 +372,20 @@ module Samagotchi
372
372
  return unless turn.on_stream_event
373
373
 
374
374
  event = { type: :generation_chunk, iteration: turn.iteration, content: chunk[:content], text: split[:text],
375
- thinking: split[:thinking], payload: chunk[:payload] }
375
+ thinking: split[:thinking], payload: event_payload(chunk[:payload]) }
376
376
  # A chunk of a tool call (its bytes are dropped from both lanes): a
377
377
  # steer doesn't cut this generation (Engine#cut_for_steer).
378
378
  event[:tool_call] = true if split[:tool]
379
379
  emit(turn, **event)
380
380
  end
381
381
 
382
+ # The payload a :generation_chunk event carries: llama.cpp's last chunk
383
+ # echoes the whole rendered prompt, which nothing reads and every SSE
384
+ # client would get (the kernel's own reads keep the full payload).
385
+ def event_payload(payload)
386
+ payload.is_a?(Hash) ? payload.except("prompt") : payload
387
+ end
388
+
382
389
  # The payload's prompt-cache counts, kept as the largest seen.
383
390
  def note_cache_counts(generation, payload)
384
391
  counts = TokenUsage.from_payload(payload)