samagotchi 0.185.0 → 0.186.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: 0b023957ca8435d102004b3163a57f3dbcaf8681961cd8cdba51788f213d9f28
4
- data.tar.gz: eabc9f853b653364ecb0203d5279cc7d04cb3b701d8151de1e91cd3256b4975f
3
+ metadata.gz: 7c27bb22f8adba8bcec2279b57fc39b85a1443b06d162bca0051a06304159f20
4
+ data.tar.gz: 6e19f8d1a5e5c97816252847d615758ef243157bf30020f350a8014c1b39169a
5
5
  SHA512:
6
- metadata.gz: 71e9afb32bba0aec30574abb010215f21b9a9b776c62ea8dc11f7416973ebb263546cde50c4e710674ab8d335f4206cfadcbc4ee8eea49ca2d1c8ee78886c807
7
- data.tar.gz: cf9e2f96d601de93db273a1ac595dc948ea81b2c2a33f330b50766c62242794706f5d30d1a744a0954f1a610c193cccff3a033741475824a68f87bcc53cdc18d
6
+ metadata.gz: c35e49b853b192912df79ad26e24f0622d27cce405ca82a43da3989c0e10bc90326a467408d23f62c45b3b8cae241d60bbda18e6dcc02f581fcaddabcc4df6a8
7
+ data.tar.gz: 48620dd50718b4d80bb2d9e6940d5f85140639aa4f975367e9abf68387e71e938f6b91d312e685db6e565140cdc06be08ed366b13e086198b0fd1269c961b39c
data/CHANGELOG.md CHANGED
@@ -8,6 +8,28 @@ and commands may change between minor versions. How releases are made:
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.186.0] - 2026-11-23
12
+
13
+ ### Added
14
+
15
+ - `reply_for` on `POST …/ask`: a thin client says what its surface can show (`"voice"`, a name from config.yml's new
16
+ `surfaces:`, or the values formatting, room, choices, detail), and the reply fits it: chi tells the model in a line
17
+ with that message, a plain surface's answer comes back without markdown (the session and the web keep the model's
18
+ text), and the next message from the web gets full formatting again. A surface without detail is told an approval,
19
+ a spending question or a user-only option in words (`needs: "detail"`), and `POST …/answer` with its `reply_for`
20
+ refuses them (403 `needs_detail`). `GET /api/info` lists `reply_for`; a session whose worker is older is refused
21
+ with 409 `reply_for_unavailable` (update chi if needed, then restart it). The iOS Shortcut recipe sends
22
+ `"reply_for": "voice"`.
23
+
24
+ ### Fixed
25
+
26
+ - Peer text: a line in a peer's text that opens like one of chi's frames is now also quoted when it is led by an
27
+ invisible character (U+3164, U+2800, combining marks, variation selectors) or a markdown list, heading or table
28
+ mark, and so is a line that opens like chi's own `Updated:` / `Attached:` notes; a peer's own `(quoted) ` prefix
29
+ stays in the shown text, and a web bubble reads the same live and after a reload for openings like `ß`.
30
+
31
+ Update with `chi update`.
32
+
11
33
  ## [0.185.0] - 2026-11-22
12
34
 
13
35
  ### Added
@@ -6791,7 +6813,8 @@ and long-lived sessions.
6791
6813
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
6792
6814
  hotkey panel that send selected text or the clipboard to your sessions.
6793
6815
 
6794
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.185.0...HEAD
6816
+ [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.186.0...HEAD
6817
+ [0.186.0]: https://github.com/dm1try/samagotchi/compare/v0.185.0...v0.186.0
6795
6818
  [0.185.0]: https://github.com/dm1try/samagotchi/compare/v0.184.0...v0.185.0
6796
6819
  [0.184.0]: https://github.com/dm1try/samagotchi/compare/v0.183.0...v0.184.0
6797
6820
  [0.183.0]: https://github.com/dm1try/samagotchi/compare/v0.182.0...v0.183.0
@@ -2188,6 +2188,24 @@ there; the new subscription replaces the dead one.
2188
2188
  (it shows the "needs chi web's access token" page; paste the token there). Pushes keep coming meanwhile.
2189
2189
  - chi web not running: no pushes (Serve answers 502; a tap couldn't open the page anyway).
2190
2190
 
2191
+ ## Surfaces: names for reply_for
2192
+
2193
+ A thin client says what its surface can show with `reply_for` on `POST …/ask`
2194
+ ([Replies that fit the surface](thin-clients.md#replies-that-fit-the-surface)):
2195
+ the values, or a name. `voice` is built in (`formatting: plain`, `room: short`,
2196
+ `choices: 3`, `detail: false`). Add names, or replace `voice`, under `surfaces:`:
2197
+
2198
+ ```yaml
2199
+ surfaces:
2200
+ watch: {formatting: plain, room: one_line, choices: 2, detail: false}
2201
+ voice: {formatting: plain, room: short, choices: 0, detail: false}
2202
+ ```
2203
+
2204
+ A value left out is the full one. chi web reads the name when the ask comes in,
2205
+ and the session saves the values, so editing a name changes the next asks, not
2206
+ old turns. A name whose values are wrong refuses only the asks that use it (400
2207
+ `invalid_ask` names the entry).
2208
+
2191
2209
  ## Unattended updates (`update.auto`)
2192
2210
 
2193
2211
  By default chi web only tells you a release is out (`update.notify`, [CLI: Updating](cli.md#updating)). With
data/docs/guardrails.md CHANGED
@@ -310,6 +310,19 @@ by editing the session file, or by running `chi --attach` on a PTY with the
310
310
  markers cleared. chi's instructions for parents ([chi as a
311
311
  sub-agent](sub-agent.md)) tell them to use `chi answer` only.
312
312
 
313
+ ### Approvals from a surface without detail
314
+
315
+ A thin client that declares `reply_for` with `detail: false` (a voice Shortcut:
316
+ [thin-clients.md](thin-clients.md#replies-that-fit-the-surface)) is told an
317
+ approval, a spending question (a hook's: cost-cap, work-cap) or a question
318
+ with `user_only` options in words (`needs: "detail"`, no options), and
319
+ `POST …/answer` with that `reply_for` refuses such a question with 403
320
+ `needs_detail` (`ReplyFor#answers?`, told by the question's `kind`, never by
321
+ its `approval:` facts, which a relayed approval may have empty). The model's
322
+ own questions and the step-limit question stay answerable. Like `client_id`,
323
+ this is a convention for an honest client, not a barrier: the token can still
324
+ answer anything, and an answer without the field is the owner's.
325
+
313
326
  ## Who may run a session command
314
327
 
315
328
  A message that is a session command (`/model x`, `!cmd`, `!rollback`) runs as the command only when a person sends
@@ -675,6 +675,7 @@ compatibility from its version. `Bridge::FEATURES` advertises:
675
675
  | `turn_ids` | A client can wait for a particular enqueued turn across running, continued and stopped turns. |
676
676
  | `verify` | The worker accepts and validates Verify anchors on turns. |
677
677
  | `revise` | The worker accepts and validates Revise anchors on turns. |
678
+ | `reply_for` | The worker saves an ask's `reply_for` (`ReplyFor`) on the turn's opener with its baked line. Without it chi web refuses the turn (409 `reply_for_unavailable`, `SessionManager#deliver_turn_now`), and with no Bridge up writes no input file unless the sidecar of a worker holding the session lists it (no sidecar, or a dead worker's leftover one: a retry); chi web lists it in `/api/info` too. |
678
679
  | `unqueue` | A client can take back a queued turn before it starts (`POST /session/:id/turn/dequeue`). |
679
680
  | `review_turns` | An older chi web checks this before sending legacy participant turns; it is not a read-only mode on current workers. |
680
681
  | `pair_turns` | The worker runs participant turns under the owner's guardrails, so chi web may invite participants. |
@@ -22,7 +22,7 @@ ivars.
22
22
  The skeleton is `Engine#run_turn` in `engine.rb`; read it for the order. Each step and what it owns:
23
23
 
24
24
  ```
25
- Engine#run_turn(session, prompt, on_event:, …, origin:, continue:, resumed:, resume_from:, verify:, revises:, …)
25
+ Engine#run_turn(session, prompt, on_event:, …, origin:, continue:, resumed:, resume_from:, verify:, revises:, reply_for:, …)
26
26
  ├── begin_turn → Turn (the TurnContext published with the running flag)
27
27
  ├── Client.swap_probe_cancel (a Stop cuts this turn's /props probes)
28
28
  ├── prepare_turn → false at a STOP CHECK (stopped_before_model), else true
@@ -652,6 +652,20 @@ model-facing copy (`strip` / `strip_all`: hooks' `messages:`, the recap, `ctx.me
652
652
  `KernelLoop#sanitize_history` and `ChatLoop#plain` copy them so the stored conversation keeps them across turns.
653
653
  `Web::App#messages_for_display` re-validates `display_refs` (`AnswerRefs.for_display`).
654
654
 
655
+ **The saved-keys rule.** `ChatLoop#plain` rebuilds every kept message from fixed key lists, earlier turns'
656
+ included: a saved message field the wire needs must be listed there (or in `ContextNote::KEYS`,
657
+ `Steer::AUTHOR_KEYS`, `ToolResponse::SAVED_KEYS`), or it is gone after its turn and the chat wires' prefix breaks.
658
+ `spec/llm/chat_loop_saved_keys_spec.rb` fails on such a field; its first turn carries a visitor's `source` and an
659
+ ask's `reply_for` / `reply_line`.
660
+
661
+ **A turn's anchors** (`TurnAnchors`: `verify`, `revises`, `reply_for`) ride from chi web to `run_turn`'s keywords
662
+ (`#kwargs`), each a flat key in the Bridge body and the input file. What a layer does with a member is its rule
663
+ (`TurnAnchors::RULES`): `holds` (an input file naming it waits for the running turn's end, never merged into it),
664
+ `participant` (shown to a participant), `turn_route` (chi web's `POST …/turn` takes it from a body: `reply_for`
665
+ is set by `POST …/ask` alone) and `vouched` (with no Bridge, its input file goes only to a worker whose sidecar
666
+ lists its feature). `reply_for` (`ReplyFor`) is saved on the opening user message with its baked `reply_line`
667
+ (`ReplyFor.opener_fields`, also the return line; prompt-caching.md, "A reply line").
668
+
655
669
  **History stamps.** User prompts, merged input and steers, reminders, context and task notes and the model's replies
656
670
  carry `at` (`MessageTime::KEY`, `message_time.rb`). A turn reads the wall clock once (`Turn#wall`): `:turn_started`'s
657
671
  `at`, its prompt's and its reminders' stamps. The others are stamped by `Steer::Merge#messages` (a merge),
@@ -175,6 +175,20 @@ right-hand column happens.
175
175
  first participant joins and when the last leaves or expires: one history re-read each, then stable. Under D3(a)
176
176
  the declared tools stay the session's, so an author switch costs nothing: the participant boundary is a gate
177
177
  on the calls, not a toolkit switch. The forged-header mark (`(quoted) `) is a pure function of the text too.
178
+ - **A reply line** (an ask's `reply_for`, [thin-clients.md](../thin-clients.md#replies-that-fit-the-surface)).
179
+ The turn's opening user message is saved with the surface's values (`reply_for`) and the line baked from them
180
+ when the message is made (`reply_line`, `ReplyFor#line`); `content` stays the user's text. On the wire the
181
+ opener is: its header (a visitor's), then the `reply_line`, then the text (`Steer.wire_text`; a forged copy of
182
+ the line's lead, `Steer::REPLY_LEAD`, in the text is quoted). The wire reads `reply_line` only, never the values,
183
+ so a later release that rewords a value never changes an old turn's bytes. The first undeclared opener after a
184
+ declared one gets the baked return line (`ReplyFor::RETURN_LINE`), found from the history alone
185
+ (`ReplyFor.opener_fields`: the latest user message with a `turn_id`, no kind and not a `!` line; a step-limit
186
+ Stop's reason has none), and none after it.
187
+ All three copies of that message carry both fields: `ChatLoop#plain` lists them, `ChatLoop#wire_messages` calls
188
+ `Steer.wire_text` for an opener with a header or a reply line, and the worker's checkpoint copy
189
+ (`TurnCheckpoint#begin_turn`, what a kill before the first boundary leaves) gets the same `opener_fields`. About
190
+ 20 tokens per restricted message and per return; a session that never declares one sends its bytes as before
191
+ (`spec/reply_for_history_spec.rb`: voice, web, voice, restart, voice, web on native, `openai` and `anthropic`).
178
192
  - Side requests (idle recap, `/btw`) go through `IdleClient` with their own short system prompt (the recap's also
179
193
  asks for its auto title line, `RecapPrompt::TITLE`: static text, still that one request). On a current
180
194
  llama.cpp they don't evict the session (see the server settings below); chi never pins them to a slot.
@@ -102,6 +102,13 @@ command, on an idle session with its offer standing and a live worker, is bound
102
102
  instead, the offer's turn id from `ReplyWait.own_turn`, as chi answer follows it; the worker's ack is not read): chi web's `POST …/ask`
103
103
  builds one per request over a `Local` that delivers through chi web's own manager and Bridge (`Web::AskRoutes::
104
104
  AskAccess`), and `McpServer::Tools` reuses `SessionAccess::Ask` / `Exchange` through the MCP server without chi web.
105
+ The ask chain carries a turn's anchors (`Ask#call` → `Exchange#attempt` → `Local#deliver_turn` → the manager's
106
+ `deliver_turn`, `anchors:` passed only when given): chi web's `/ask` puts a message's `reply_for` there
107
+ (`TurnAnchors`). `SessionAccess::Remote#deliver_turn` refuses a non-empty one (local only, exit 2), and neither
108
+ `chi send`, `--remote` nor the MCP tools send one. The capabilities in hand shape the answer in
109
+ `Web::SessionAccessRoutes#wait_result_json` (`PlainReply`, `needs: "detail"`): the request's for `/ask`, the
110
+ token's (`Exchange::Token`'s `f`, `Token.reply_for`) for `/wait`, the pending turn's saved opener's
111
+ (`ReplyFor.of_latest_turn`, read before the answer is relayed) for `/answer`'s reply.
105
112
  An ask's `request_id` becomes its turn's enqueued id (`SessionInbox.enqueued_id_for("ask:" + it)`, a UUID v5 shape a
106
113
  Bridge keeps): `Ask#call` first reads `prepare_wait(turn: E)`, and a `known_turn` (running, a queued input file, the
107
114
  last to end, a reply file, settled, merged) is waited on again with `Target.wait_only(start, requested: E).with(queued:)`, nothing
data/docs/thin-clients.md CHANGED
@@ -59,10 +59,74 @@ another link ran it. Body fields:
59
59
  prompt gets that turn's answer and nothing is sent; otherwise a worker that
60
60
  remembers the key answers 409 `enqueued_id_conflict`. An answer that echoes
61
61
  `request_id` means chi web used it (an older chi web ignores the field).
62
+ - `reply_for`: what your surface can show, so the reply fits it. See
63
+ [Replies that fit the surface](#replies-that-fit-the-surface).
62
64
 
63
65
  A question that is waiting for an answer refuses the ask with 409 `waiting` and
64
66
  the `question`. Answer it first (below).
65
67
 
68
+ ## Replies that fit the surface
69
+
70
+ A voice Shortcut can't show a table, and a widget has room for one line. Say so
71
+ with `reply_for` on the ask: a name, or the values themselves.
72
+
73
+ ```sh
74
+ curl -s -H "Authorization: Bearer $T" -H 'Content-Type: application/json' \
75
+ -X POST http://192.168.1.29:4567/api/sessions/3fa2/ask -d '{"prompt": "status?", "reply_for": "voice"}'
76
+ # {"status": "done", "text": "Three commits are in. The rm command works, …", …}
77
+ ```
78
+
79
+ The values (a missing one is the full value, as the web has):
80
+
81
+ | value | full | restricted |
82
+ |---|---|---|
83
+ | `formatting` | `markdown` | `plain`: no markdown, no emoji, no links |
84
+ | `room` | `long` | `short` (at most 60 words), `one_line` (at most 80 characters, one sentence of 15 words or fewer) |
85
+ | `choices` | `many` | `0` to `9`: how many options a question may offer |
86
+ | `detail` | `true` | `false`: no commands, code or diffs, and no approvals (below) |
87
+
88
+ `"reply_for": "voice"` is `{"formatting": "plain", "room": "short", "choices": 3,
89
+ "detail": false}`. Name your own in config.yml's
90
+ [`surfaces:`](configuration.md#surfaces-names-for-reply_for), for example
91
+ `"reply_for": "watch"`. A name is read when the ask comes in, and the session
92
+ saves its values, so a later config edit doesn't change old turns. An unknown
93
+ name, key or value is 400 `invalid_ask`.
94
+
95
+ What happens:
96
+
97
+ - chi tells the model in a line with your message, and the reply is written
98
+ for the surface. The session keeps one answer per turn: the web shows this
99
+ short one too. Ask again on the web for the long one.
100
+ - With `formatting: plain` the answer you get has its markdown taken out (list
101
+ bullets, bold, code marks, headings, tables, link URLs, emoji; a numbered
102
+ list keeps its numbers). So does a question's text and header; its options
103
+ stay exactly as they are, since you answer by label. Only your answer: the
104
+ session, the web and the terminal keep the model's text. A `token` you wait
105
+ on keeps doing this.
106
+ - The next message from the web or the terminal gets full formatting again: chi
107
+ tells the model once.
108
+ - Each message declares its own: send `reply_for` on every ask from that
109
+ surface. A message with it always runs as its own turn (with `queue: false`,
110
+ a running session is 409 `busy` as usual).
111
+
112
+ **Questions.** A surface with `detail: false` gets the model's own questions and
113
+ the "continue or stop?" question as usual. An approval, a spending question
114
+ (cost-cap, work-cap) or a question whose options only you may pick answers
115
+ `"status": "waiting_for_answer"` with `"needs": "detail"`, a `text` to speak
116
+ ("chi needs an approval: open it on a full screen.") and the question's `id` and
117
+ `kind` only. Open it in chi web (the phone notification takes you there). The 409
118
+ `waiting` of a later ask says the same. `POST …/answer` takes `reply_for` too:
119
+ with `detail: false` such a question is 403 `needs_detail`, nothing answered.
120
+ Like `client_id`, this is a convention for an honest client: the token itself
121
+ can still answer anything.
122
+
123
+ **Older chi.** Check `GET /api/info` lists `"reply_for"` in its `features`. An
124
+ older chi web ignores the field and answers 200 with a full reply. A chi web
125
+ that has it refuses a session whose worker is older with 409
126
+ `reply_for_unavailable`, and nothing is sent: update chi if needed, then
127
+ restart the session (`chi sessions restart ID`). A session restarts on the chi
128
+ that made it, so a restart alone may not be enough.
129
+
66
130
  ## When the answer takes longer
67
131
 
68
132
  Each call answers within **35 seconds** of its request, whatever it waits for
@@ -157,14 +221,15 @@ answers the first turn.
157
221
  1. **Dictate Text** (or **Ask for Input**).
158
222
  2. **Get Contents of URL**: `https://<your chi web>/api/sessions/<id>/ask`,
159
223
  method POST, header `Authorization: Bearer <token>`, JSON body `prompt` =
160
- the dictated text. To survive a dropped connection, first **Set Variable**
224
+ the dictated text and `reply_for` = `voice`. To survive a dropped connection, first **Set Variable**
161
225
  `key` to **Current Date** formatted with seconds, send `request_id` = `key`,
162
226
  and if the step fails (no `status` in the answer) run it again with the same
163
227
  `key`: the retry answers the first one's turn instead of sending it twice.
164
228
  3. **Repeat** while the answer's `status` is `timeout`: **Get Contents of URL**
165
229
  for `…/api/sessions/<session_id>/wait` with the JSON body `token` = the
166
230
  answer's `token`.
167
- 4. **Get Dictionary Value** `text`, then **Speak Text**.
231
+ 4. **Get Dictionary Value** `text`, then **Speak Text**. With `needs` =
232
+ `detail` the text says to open chi on a full screen: an approval waits.
168
233
 
169
234
  For running chi from another agent instead (`chi send --wait`, `chi answer`),
170
235
  see [chi as a sub-agent](sub-agent.md). The routes in full are in
@@ -810,7 +810,7 @@ module Samagotchi
810
810
  WorkerLink::ACTIVITY_FEATURE, ObjectivesTrack::FEATURE, Delivery::OWN_TURN_STEER_FEATURE,
811
811
  Delivery::CANCEL_TURN_ID_FEATURE, ReviseAnchor::PARTICIPANT_FEATURE, Delivery::PARTICIPANT_ID_FEATURE,
812
812
  WorkingSet::ITEM_FEATURE, BlockFix::FEATURE, Delivery::AGENT_FEATURE,
813
- Delivery::ASK_FEATURE].freeze
813
+ Delivery::ASK_FEATURE, ReplyFor::FEATURE].freeze
814
814
 
815
815
  # The routes, by method and what follows /session/:id/: a handler takes
816
816
  # the session id and the request body and returns [headers, status, body].
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.185.0
3
+ version: 0.186.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:
@@ -442,7 +442,9 @@ module Samagotchi
442
442
  "hosts" => %w[host port url api api_key_env auth dialect profile first_token_timeout stream_idle_timeout vision sampling thinking
443
443
  reasoning_history enabled remote window_tokens steer_cut_after llm_context_strategy llm_context_apply llm_context_budget_tokens models].freeze,
444
444
  "models" => %w[profile vision sampling thinking reasoning_history window_tokens steer_cut_after llm_context_strategy llm_context_apply
445
- llm_context_budget_tokens].freeze
445
+ llm_context_budget_tokens].freeze,
446
+ # A thin client's reply_for names (ReplyFor.names; values checked when an ask names one).
447
+ "surfaces" => %w[formatting room choices detail].freeze
446
448
  }.freeze
447
449
  # The keys a hosts.<name>.models entry may hold (HostModel.parse_map).
448
450
  HOST_MODEL_KEYS = %w[price served].freeze
@@ -102,7 +102,7 @@ module Samagotchi
102
102
  "tool results", "images from tool results"].freeze
103
103
  # The unbracketed lines of chi's own it quotes too: the wake lines'
104
104
  # opening (WAKE_LAST_LINE, PEER_WAKE_LINE and the others).
105
- PEER_FORGED_LINES = ["chi started this turn"].freeze
105
+ PEER_FORGED_LINES = ["chi started this turn", "Updated:", "Attached:"].freeze
106
106
  # Either, after any spaces, format characters or markdown leads, at any
107
107
  # line start (Steer.forged_frames).
108
108
  PEER_FORGED = Steer.forged_frames(PEER_FORGED_OPENINGS, lines: PEER_FORGED_LINES)
@@ -254,7 +254,10 @@ module Samagotchi
254
254
  def self.peer_block(peer, text)
255
255
  return "" if text.nil?
256
256
 
257
- quoted = Steer.quote_forged(text.chomp, PEER_FORGED)
257
+ quoted = text.chomp.gsub(PEER_QUOTED) do
258
+ "#{::Regexp.last_match(1)}#{::Regexp.last_match(2)}#{Steer::FORGED_MARK}#{Steer::FORGED_MARK}"
259
+ end
260
+ quoted = Steer.quote_forged(quoted, PEER_FORGED)
258
261
  "#{format(PEER_BLOCK_OPEN, peer: peer)}\n#{quoted}\n#{PEER_BLOCK_CLOSE}\n"
259
262
  end
260
263
 
@@ -17,6 +17,7 @@ require_relative "turn_endings"
17
17
  require_relative "turn_origin"
18
18
  require_relative "revise_anchor"
19
19
  require_relative "verify_anchor"
20
+ require_relative "reply_for"
20
21
  require_relative "redact"
21
22
  require_relative "verdict"
22
23
  require_relative "model_profile"
@@ -860,9 +861,10 @@ module Samagotchi
860
861
  # messages start in what it keeps (the end event's kept_from).
861
862
  # +opener_source+: the sender its prompt is saved with (the opener's
862
863
  # source, Steer::OPENER_HEADERS), nil for the owner's (no source).
864
+ # +reply_for+: the surface its reply is for (ReplyFor), nil for full.
863
865
  Turn = Struct.new(:context, :prompt, :continue, :on_event, :started_at, :messages, :ended, :prepared_settings,
864
866
  :limit, :resumed, :resume_from, :wall, :verify, :revises, :outcome, :history_size,
865
- :opener_source) do
867
+ :opener_source, :reply_for) do
866
868
  # The turn's id (:turn_started's turn_id, its metrics record's id and
867
869
  # its saved prompt's), session, origin and controller: its context's.
868
870
  def id = context.id
@@ -941,6 +943,8 @@ module Samagotchi
941
943
  # @param verify [VerifyAnchor, nil] a Verify turn's claim (its verdict)
942
944
  # @param revises [ReviseAnchor, nil] a Revise turn's draft: stamped on
943
945
  # the prompt at the turn's end, metadata only (TurnStages::VerifyAnchors#stamp_opening)
946
+ # @param reply_for [ReplyFor, Hash, nil] what the asking surface shows:
947
+ # saved on the prompt with its baked line (ReplyFor.opener_fields)
944
948
  #
945
949
  # An Interrupt (SIGINT) cancels the turn: what it got to is kept in the
946
950
  # session as after a Stop (the prompt, the loop's finished tool
@@ -953,11 +957,12 @@ module Samagotchi
953
957
  # one-line summary:.
954
958
  def run_turn(session, prompt, on_event: nil, max_iterations: nil, cancel_controller: nil, max_tool_output_chars: nil, pending_input: nil, continue: false,
955
959
  origin: TurnOrigin::NONE, images: [], id: nil, resumed: false, resume_from: nil, verify: nil, revises: nil,
956
- input_waiting: nil, opener_source: nil)
960
+ input_waiting: nil, opener_source: nil, reply_for: nil)
957
961
  turn = begin_turn(session, prompt, on_event: on_event, cancel_controller: cancel_controller, origin: origin,
958
962
  continue: continue, id: id, verify: verify, revises: revises,
959
963
  input_waiting: input_waiting)
960
964
  turn.opener_source = opener_source.to_s unless opener_source.to_s.empty?
965
+ turn.reply_for = ReplyFor.from(reply_for)
961
966
  if continue
962
967
  turn.resumed = resumed
963
968
  turn.resume_from = resume_from
@@ -1212,6 +1217,8 @@ module Samagotchi
1212
1217
  # Only an opener from a sender the model reads a header for
1213
1218
  # (Steer::OPENER_HEADERS): the owner's keeps its bytes.
1214
1219
  user_message[:source] = turn.opener_source if turn.opener_source
1220
+ # The surface's values and the line the model reads (none: its bytes as they were).
1221
+ user_message.merge!(ReplyFor.opener_fields(session.messages, turn.reply_for))
1215
1222
  turn.messages << user_message
1216
1223
  session.last_prompt = turn.prompt
1217
1224
  end
@@ -21,6 +21,7 @@ require_relative "../cut_policy"
21
21
  require_relative "../context_status"
22
22
  require_relative "../context_window"
23
23
  require_relative "../context_note"
24
+ require_relative "../reply_for"
24
25
  require_relative "../tool_output_cut"
25
26
  require_relative "../tool_runner"
26
27
  require_relative "../tool_response"
@@ -261,8 +262,9 @@ module Samagotchi
261
262
  wire << system_message(entry, index)
262
263
  end
263
264
  when "user"
264
- # A steer or merged input (always a String) goes with its header.
265
- content = Steer.header(entry) ? Steer.wire_text(entry, entry[:content].to_s) : entry[:content]
265
+ # A steer or merged input (always a String) goes with its header,
266
+ # an opener with its header or its reply line (Steer.wire_text).
267
+ content = Steer.header(entry) || Steer.reply_line(entry) ? Steer.wire_text(entry, entry[:content].to_s) : entry[:content]
266
268
  wire << { role: "user", content: parts(content, items) }
267
269
  when "model"
268
270
  message = assistant_message(entry, paired)
@@ -478,6 +480,15 @@ module Samagotchi
478
480
  # find_tools result's loaded names and a tool change's TOOL_CHANGE
479
481
  # (sent only to a wire that loads tools), and an entry's wall time
480
482
  # (MessageTime::KEY, display-only, never sent).
483
+ #
484
+ # The rule: a saved message field the wire needs must be listed here
485
+ # (a key below, or one of the lists it reads: ContextNote::KEYS,
486
+ # Steer::AUTHOR_KEYS, ToolResponse::SAVED_KEYS). This rebuilds every
487
+ # kept message, earlier turns' included, from these keys alone: an
488
+ # unlisted field is gone from the saved history once its turn ends,
489
+ # so the next request reads that message without it and the chat
490
+ # wires' prompt prefix breaks (a visitor opener's +source+ header,
491
+ # say). spec/llm/chat_loop_saved_keys_spec.rb fails on such a field.
481
492
  def plain(conversation)
482
493
  conversation.map do |entry|
483
494
  content = entry[:content].is_a?(Array) ? entry[:content] : entry[:content].to_s
@@ -490,6 +501,9 @@ module Samagotchi
490
501
  message[:turn_start] = true if entry[:turn_start] == true
491
502
  message[:verify] = entry[:verify] if entry[:verify].is_a?(Hash)
492
503
  message[:revises] = entry[:revises] if entry[:revises].is_a?(Hash)
504
+ # An opener's surface (ReplyFor) and the line baked from it, which the wire reads.
505
+ message[ReplyFor::MESSAGE_KEY] = entry[ReplyFor::MESSAGE_KEY] if entry[ReplyFor::MESSAGE_KEY].is_a?(Hash)
506
+ message[ReplyFor::LINE_KEY] = entry[ReplyFor::LINE_KEY] if entry[ReplyFor::LINE_KEY].is_a?(String)
493
507
  message[:thinking] = entry[:thinking] if entry[:thinking].is_a?(String) && !entry[:thinking].empty?
494
508
  message[:anthropic_content] = entry[:anthropic_content] if entry[:anthropic_content].is_a?(Array)
495
509
  ToolResponse::SAVED_KEYS.each { |key| message[key] = entry[key] if entry[key] }
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ # A reply made plain for a surface that shows plain text only (ReplyFor
5
+ # formatting "plain": a voice Shortcut reads it aloud). Deterministic: the
6
+ # same text gives the same output. On the way out only, in chi web's wait
7
+ # answers (SessionAccessRoutes#wait_result_json); the saved reply, the
8
+ # reply file, the SSE stream and the web bubble keep the model's text.
9
+ #
10
+ # What goes: a heading's, a bullet's and a quote's lead, a table's pipes
11
+ # (a separator row whole), a rule line, ** and __, backticks, a link's URL
12
+ # (its text kept), emoji. What stays: a numbered list's numbers ("1. "),
13
+ # which read well aloud, and a fenced code block's content, byte for byte
14
+ # (its fence lines go; one never closed runs to the end).
15
+ module PlainReply
16
+ # A fence's opening line: its marker (``` or ~~~, three or more). A
17
+ # backtick fence's info string holds no backtick (CommonMark), so a
18
+ # line like "```ls -la``` lists files" is inline code, not a fence.
19
+ FENCE_OPEN = /\A[ \t]*(`{3,}(?=[^`]*\z)|~{3,})/
20
+ HEADING = /^([ \t]*)\#{1,6}[ \t]+/
21
+ BULLET = /^([ \t]*)[-*+][ \t]+/
22
+ QUOTE = /^([ \t]*)(?:>[ \t]?)+/
23
+ RULE = /^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*(\n|\z)/
24
+ TABLE_SEPARATOR = /^[ \t]*\|?[ \t]*:?-{3,}:?[ \t]*(\|[ \t]*:?-{3,}:?[ \t]*)*\|?[ \t]*(\n|\z)/
25
+ TABLE_ROW = /^[ \t]*\|(.*?)\|?[ \t]*$/
26
+ LINK = /\[([^\]\n]+)\]\([^)\s]+(?:[ \t]+"[^"]*")?\)/
27
+ EMPHASIS = /\*\*|__/
28
+ EMOJI = /[ \t]?[\u{1F000}-\u{1FAFF}\u{2600}-\u{27BF}\u{2B00}-\u{2BFF}\u{FE0F}\u{200D}]+/
29
+
30
+ module_function
31
+
32
+ # @param text [String, nil]
33
+ # @return [String, nil] nil for nil
34
+ def strip(text)
35
+ return text if text.nil?
36
+
37
+ lines = segments(text.gsub("\r\n", "\n")).flat_map do |code, body|
38
+ next body if code || body.empty?
39
+
40
+ plain(body.join("\n")).split("\n", -1).map { |line| line.rstrip.sub(/\A[ \t]+/, "") }
41
+ end
42
+ lines = lines.drop_while { |line| line.strip.empty? }
43
+ lines.pop while lines.last&.strip&.empty?
44
+ lines.join("\n")
45
+ end
46
+
47
+ # +text+'s lines as [code?, lines] runs: a fence's content (code) and
48
+ # the text between fences, the fence lines left out.
49
+ # @return [Array<Array(Boolean, Array<String>)>]
50
+ def segments(text)
51
+ runs = [[false, []]]
52
+ close = nil
53
+ text.split("\n", -1).each do |line|
54
+ if close&.match?(line)
55
+ close = nil
56
+ runs << [false, []]
57
+ elsif !close && (open = FENCE_OPEN.match(line))
58
+ close = /\A[ \t]*#{Regexp.escape(open[1][0])}{#{open[1].size},}[ \t]*\z/
59
+ runs << [true, []]
60
+ else
61
+ runs.last.last << line
62
+ end
63
+ end
64
+ runs
65
+ end
66
+
67
+ # A text run made plain (no fence in it).
68
+ def plain(text)
69
+ out = text.gsub(TABLE_SEPARATOR, "").gsub(RULE, "")
70
+ out = out.gsub(TABLE_ROW) { Regexp.last_match(1).split("|").map(&:strip).reject(&:empty?).join(", ") }
71
+ out = out.gsub(HEADING, '\1').gsub(BULLET, '\1').gsub(QUOTE, '\1')
72
+ out.gsub(LINK, '\1').gsub(EMPHASIS, "").delete("`").gsub(EMOJI, "")
73
+ end
74
+ end
75
+ end