samagotchi 0.185.0 → 0.187.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 (67) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -1
  3. data/bin/chi +2 -0
  4. data/docs/cli.md +1 -0
  5. data/docs/configuration.md +18 -0
  6. data/docs/guardrails.md +13 -0
  7. data/docs/internals/bridge.md +1 -0
  8. data/docs/internals/engine.md +15 -1
  9. data/docs/internals/inline-widgets.md +18 -0
  10. data/docs/internals/pages.md +172 -0
  11. data/docs/internals/prompt-caching.md +14 -0
  12. data/docs/internals/remote-sessions.md +7 -0
  13. data/docs/internals/web-frontend.md +5 -4
  14. data/docs/memory.md +7 -0
  15. data/docs/pages.md +150 -0
  16. data/docs/thin-clients.md +67 -2
  17. data/lib/samagotchi/bridge.rb +1 -1
  18. data/lib/samagotchi/bundles/system/manifest.yml +5 -2
  19. data/lib/samagotchi/bundles/system/self_map.md +5 -1
  20. data/lib/samagotchi/bundles/system/skill_pages.md +93 -0
  21. data/lib/samagotchi/config.rb +3 -1
  22. data/lib/samagotchi/context_absorber.rb +5 -2
  23. data/lib/samagotchi/engine.rb +9 -2
  24. data/lib/samagotchi/inline_widgets.rb +65 -0
  25. data/lib/samagotchi/llm/chat_loop.rb +16 -2
  26. data/lib/samagotchi/page_command.rb +234 -0
  27. data/lib/samagotchi/pages/builder.rb +187 -0
  28. data/lib/samagotchi/pages/launch.rb +187 -0
  29. data/lib/samagotchi/pages/runner.rb +154 -0
  30. data/lib/samagotchi/pages/store.rb +143 -0
  31. data/lib/samagotchi/pages.rb +119 -0
  32. data/lib/samagotchi/plain_reply.rb +75 -0
  33. data/lib/samagotchi/reply_for.rb +254 -0
  34. data/lib/samagotchi/run_options.rb +1 -0
  35. data/lib/samagotchi/session_access/ask.rb +5 -2
  36. data/lib/samagotchi/session_access/contract.rb +1 -1
  37. data/lib/samagotchi/session_access/exchange/token.rb +42 -7
  38. data/lib/samagotchi/session_access/exchange.rb +5 -2
  39. data/lib/samagotchi/session_access/local.rb +4 -2
  40. data/lib/samagotchi/session_access/remote.rb +5 -1
  41. data/lib/samagotchi/session_manager/delivery.rb +36 -6
  42. data/lib/samagotchi/steer.rb +30 -8
  43. data/lib/samagotchi/turn_anchors.rb +65 -17
  44. data/lib/samagotchi/turn_checkpoint.rb +5 -3
  45. data/lib/samagotchi/version.rb +1 -1
  46. data/lib/samagotchi/web/app.rb +6 -6
  47. data/lib/samagotchi/web/ask_routes.rb +62 -17
  48. data/lib/samagotchi/web/page_routes.rb +116 -0
  49. data/lib/samagotchi/web/participant_access.rb +1 -1
  50. data/lib/samagotchi/web/public/app.js +24 -84
  51. data/lib/samagotchi/web/public/index.html +3 -0
  52. data/lib/samagotchi/web/public/page_blocks.js +58 -0
  53. data/lib/samagotchi/web/public/page_links.js +33 -0
  54. data/lib/samagotchi/web/public/page_model.js +68 -0
  55. data/lib/samagotchi/web/public/page_route.js +24 -0
  56. data/lib/samagotchi/web/public/page_table.js +74 -0
  57. data/lib/samagotchi/web/public/page_table_model.js +76 -0
  58. data/lib/samagotchi/web/public/page_view.js +218 -0
  59. data/lib/samagotchi/web/public/pages.css +77 -0
  60. data/lib/samagotchi/web/public/pages_group.js +65 -0
  61. data/lib/samagotchi/web/public/peer_text.js +22 -5
  62. data/lib/samagotchi/web/public/views.js +161 -0
  63. data/lib/samagotchi/web/session_access_routes.rb +30 -2
  64. data/lib/samagotchi/web/session_control.rb +21 -2
  65. data/lib/samagotchi/web/viewer.rb +1 -1
  66. data/lib/samagotchi/worker.rb +2 -1
  67. metadata +23 -1
data/docs/pages.md ADDED
@@ -0,0 +1,150 @@
1
+ # Pages: scripts that say what to show
2
+
3
+ A page is a Ruby script that gets its data any way a script can (another program's `--format json`, a file, the
4
+ session files) and hands rows and text to `ui`. `chi page run NAME` runs it and stores what it built; what shows a
5
+ page draws from that stored result, so showing it runs nothing. Pages run from the terminal and show in chi web, where
6
+ Refresh runs them again ([In chi web](#in-chi-web)).
7
+
8
+ **A page is code you trust.** It runs as you, with your files and your network, like any Ruby script chi writes for
9
+ you. There is no sandbox.
10
+
11
+ ## Asking chi for a page
12
+
13
+ Say what you want to see and that you want it kept: "make me a page of …", "I'd like to reopen this in the web: …",
14
+ "keep this as a page". chi follows its shipped pages skill (`skill_pages`, [docs/memory.md](memory.md#skills)): it
15
+ finds the pages folder with `chi self`, writes `NAME.rb` there, runs `chi page run NAME`, compares the stored rows
16
+ with where they came from, fixes what failed, and answers in a line or two with the link `[Title](#/p/NAME)` (with
17
+ Markdown off, the link is plain text: the page is in All sessions, under Pages). "Change the page …" edits the script
18
+ and runs it again; "remove the page …" is `chi page rm NAME`.
19
+
20
+ - It uses `chi page list`, the read tool, `chi page run` and `chi page rm`, never a shell command that names the pages
21
+ folder (those ask you, and a turn nobody watches stops there).
22
+ - **Strict mode** (`guardrails.mode: strict`): writing the script asks (`write-outside-repo`: you, or whoever may
23
+ answer for the session, such as a parent agent or System 1); if it is denied, chi says so and stops.
24
+ - A participant's turn ([chi share](cli.md)) can't write chi's config folder or run chi commands: a page asked for
25
+ there is refused.
26
+
27
+ ## A page
28
+
29
+ ```ruby
30
+ # ~/.config/samagotchi/pages/usage.rb
31
+ page "Usage, last 7 days" do |ui|
32
+ data = JSON.parse(`chi-usage --days 7 --format json`)
33
+ ui.text "Stored cost per model. #{data["totals"]["turns"]} turns."
34
+ ui.table data["groups"].map { |model, g| g.merge("model" => model) },
35
+ columns: { "model" => "Model", "turns" => "Turns", "cost" => "Stored" },
36
+ format: { "cost" => :money }, key: %w[turns cost],
37
+ total: { "model" => "Total", "turns" => data["totals"]["turns"], "cost" => data["totals"]["cost"] }
38
+ end
39
+ ```
40
+
41
+ ```
42
+ $ chi page run usage
43
+ page usage: "Usage, last 7 days" (0.4 s)
44
+ - text: Stored cost per model. 412 turns.
45
+ - table, 3 rows, columns: Model, Turns, Stored
46
+ claude:sonnet-5-5 | 96 | $14.2210
47
+ openrouter:deepseek-v4 | 141 | $3.9042
48
+ splash:qwen3.8-flash-next | 175 | $0.0000
49
+ total: Total | 412 | $18.1252
50
+ ```
51
+
52
+ The file is `NAME.rb` under `~/.config/samagotchi/pages/` (`$XDG_CONFIG_HOME/samagotchi/pages/`). A name is lowercase
53
+ letters, digits and hyphens, a letter or a digit first, at most 40. `json` is loaded; `require` anything else you use.
54
+
55
+ ## What `ui` takes
56
+
57
+ A script calls `page "Title" do |ui| … end` once: a second call, or none, fails the run. The blocks show in the order
58
+ the script adds them, at most 20.
59
+
60
+ - **`ui.text(markdown)`**: a text block, Markdown. At most 16 KB.
61
+ - **`ui.table(rows, columns:, format: {}, key: nil, total: nil)`**: a table.
62
+ - `rows`: a list of Hashes (string or symbol keys). At most 500 are kept; the rest are dropped and the page says how
63
+ many.
64
+ - `columns:` (required) a Hash `key => label` in the order to show, or a list of keys (the label is the key). At most
65
+ 12.
66
+ - `format:` `key => :money` (`$14.2210`) or `:count` (`1.2k`, `3.4M`). Nothing else: format other columns as text
67
+ yourself. The stored cell stays the number, so the column still sorts as numbers.
68
+ - `key:` the columns a phone shows before a row is opened, besides the first column, which always shows. Without it:
69
+ the first two columns whose cells are all numbers or empty.
70
+ - `total:` a Hash by column key, shown as a last row.
71
+ - A cell: a number stays a number, `nil` shows blank (`—` in the terminal), `true`/`false` stay, anything else is
72
+ its text (NaN and Infinity too). A cell over 300 characters is cut with `…`.
73
+ - **`ui.walk(title:, actors:, steps:)`** (or one Hash): a scenario walk, the same data and rules as a `chi-ui` walk in
74
+ an answer ([inline widgets](internals/inline-widgets.md#the-schemas)), drawn by the same widget. A walk the schema
75
+ refuses fails the run with its reason.
76
+
77
+ A rule broken fails the run with a message naming the block and the limit: `table 2: column "cost" has format
78
+ :percent (use :money or :count)`, `table 1 has 13 columns (at most 12)`.
79
+
80
+ ## Running
81
+
82
+ - `chi page run NAME` runs the script in a Ruby process of its own and prints a summary of each block: a text's first
83
+ lines, a table's labels, first rows and total, a walk's step count. `--format json` prints the stored page.
84
+ - A run that fails (the script raised, has a syntax error, called `exit`, broke a limit, or printed more than 256 KB of
85
+ blocks) prints `error: line 9: undefined method 'fetch' for nil`, the last lines of what the script wrote to stderr,
86
+ and exits 1. **The result of the last good run is kept**: a bad edit never blanks the page.
87
+ - A run still going at **30 s** is stopped, with everything it started; the error says so. If what started the run
88
+ dies first (a killed terminal or chi web), the run stops itself a few seconds after its 30 s and records the same
89
+ error. Its output then has nowhere to go: a script that prints a lot may fail with `Broken pipe` instead (the last
90
+ good result is kept).
91
+ - One run of a page at a time: a second `chi page run usage` meanwhile exits 1 with `page usage is already running`.
92
+ - `chi page list` shows each page's title and `ran 2 min ago`, `failed 1 h ago (line 9)` or `(never ran)`, with
93
+ `changed` when the script changed since its result was made (the result came from an older script; nothing ran). `chi page rm NAME` removes the script and its result.
94
+
95
+ Exit codes: 0 ran, 1 failed (or no such page, or already running), 2 the command line itself (an unknown flag, a name
96
+ that breaks the rule). See [the CLI](cli.md#commands).
97
+
98
+ ## In chi web
99
+
100
+ - **Finding a page.** All sessions has a **Pages** group at its top, in every project scope (pages are global): one row
101
+ of cards that scrolls sideways, each with the page's title and `ran 2 min ago`, `failed 1 h ago` or `never ran`. The
102
+ search field filters it too, by name and title. With no page (or none the search matches) there is no group. A
103
+ `#/p/usage` link in chi's answer opens the page in the same tab; a reload or a copied `…/#/p/usage` link opens it
104
+ too.
105
+ - **The page** shows in place of the session area: Back (to where it was opened from, else All sessions), the title,
106
+ when it ran and how long it took, **Refresh** and `⋯` with Delete (it asks once, then removes the script and its
107
+ result). Opening it shows the stored result at once and runs nothing.
108
+ - **Refresh** runs the script as `chi page run` does and redraws when the run ends; the button reads "Running…" and
109
+ can't be pressed twice. A run already going (from a terminal, another tab) says "already running". Stopping chi web
110
+ stops a Refresh. A Refresh holds its request until the run ends, up to about 32 s (the 30 s cut and its grace): behind
111
+ an auth proxy ([configuration.md](configuration.md#behind-an-auth-proxy)), its timeout must allow that.
112
+ - **A failed run** keeps the last result, dimmed, under "The script failed at line 9: … Showing the result from 21
113
+ Nov, 14:02." with **Copy the error** (the line, the message and the script's last words on stderr).
114
+ - **The script changed** since the result on screen was made: a line says so; nothing has run. "Changed" means the
115
+ result came from an older script.
116
+ - **A table**: a column header sorts by it (numbers as numbers, blanks last, the total stays at the bottom); a wide
117
+ table scrolls sideways in its own box. On a phone each row shows the first column and the key columns (`key:`);
118
+ a tap opens the rest as label and value lines; rows keep the script's order there.
119
+ - **A walk** is drawn by the same widget as in an answer; its lanes scroll sideways inside it.
120
+ - **Markdown off** (`web.markdown`, the default): a text block shows as plain text, and a link in chi's answer is plain
121
+ text too, so the Pages group is the way in. A fenced block inside a text block (a `chi-ui` or a mermaid one) stays
122
+ source on a page.
123
+ - **Not live**: the group is read when All sessions opens, a page when it opens and after its own Refresh or Delete.
124
+ A run from a terminal shows after the next open or a reload.
125
+ - Pages are the owner's: a participant ([chi share](cli.md)) sees no Pages group, no page, and no page route answers
126
+ their link.
127
+
128
+ ## Where a run happens
129
+
130
+ - **The working folder is the pages folder.** A chi command a script runs sees that folder's project: if
131
+ `~/.config` sits in a git repository, that repository. Pass `--scope=all` to the session commands
132
+ (`chi sessions list --scope=all --format json`) for every project.
133
+ - **The environment is yours**, as a session's worker gets it: the XDG folders absolute, chi's own session markers and
134
+ guardrails settings left out, and `PWD` the pages folder; chi web's Refresh runs chi web's own chi. `CHI_REMOTE`, a worker's `SAMAGOTCHI_WORKER_*` keys and
135
+ the agent markers (`CLAUDECODE`, `CODEX_THREAD_ID`, `AI_AGENT`) are left out too: a run is always on this machine,
136
+ and a `chi send` from a script is yours, even when chi was started from an agent's pane. Name `chi` plainly; name other programs by absolute path:
137
+ a Refresh in chi web runs with chi web's `PATH`, which may not be your shell's.
138
+ - What the script prints to stdout is its own: the result goes through the stored file. Its stderr shows under a
139
+ failure.
140
+ - **A child that leaves the process group survives the 30 s cut** (a `setsid` or a daemon). A program the script
141
+ starts (`spawn`, `system`, backticks) never keeps the page "already running"; a Ruby `fork` (or `Process.daemon`)
142
+ that lives on does, until it ends. A script that `exec`s another program hands the run to it: the 30 s cut still
143
+ applies, but if what started the run dies, nothing stops that program. Anything that stays in the group is stopped.
144
+
145
+ ## Where things are stored
146
+
147
+ - The script: `~/.config/samagotchi/pages/NAME.rb`.
148
+ - The result: `~/.local/state/samagotchi/pages/NAME/output.json` (`$XDG_STATE_HOME`): the title, the blocks of the last
149
+ good run, when it ran, how long it took, the sha256 of the script that made it, and the last failure since, if any.
150
+ Its shape is in [internals/pages.md](internals/pages.md).
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,11 +1,14 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.185.0
3
+ version: 0.187.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:
7
7
  identity.md: sha256:29c2f7df9f6c5acbc5ec17000a4490741e55e426af15ca0d81c8706edd9bd027
8
- self_map.md: sha256:14894ec889a4c8b982023d375515b1ba51e661a3c6b5059f1a6135caee821832
8
+ self_map.md: sha256:c46fefc568b9b57c907ecc04f34b181dcc92d1cbcc40ef878a66b3973d79792f
9
9
  config_modification_protocol.md: sha256:03fdf3ea3138449bc73f73eaa5604cc5d702777c20499ec13ca32b7696e6d37f
10
10
  memory_guide.md: sha256:272443ff8292631b28239cb8431d6e8dd19aa23fc53d05e1a10c11696a0a5d8d
11
11
  delegated.md: sha256:a0d6ddcd4a8be06526d964898611775fd251cfd9d145a9d16afaccaa503597bd
12
+ skill_pages.md:
13
+ sha256: sha256:be6071ce6195ffb3c8340cb458fd5d181f9ef86c87bda44b840f7bf066648478
14
+ description: "Make, change or remove a page in chi web (a table, text or a walk the user reopens at #/p/NAME): write the script, chi page run, check, link"
@@ -70,6 +70,10 @@
70
70
  tell the user to restart the session. The plugin API: `docs/plugins.md`; what each shipped bundle does: `docs/bundles.md`. Writing one: read
71
71
  `docs/bundle-authoring.md` in my source dir first.
72
72
 
73
+ - Pages: `chi page run|list|rm` runs, lists and removes pages, Ruby scripts in the `pages/` folder beside the
74
+ config file whose stored result chi web shows at `#/p/NAME`; how I make one is the `skill_pages` memory
75
+ (`docs/pages.md`).
76
+
73
77
  An MCP host or a script can drive me: `docs/mcp-server.md`, `docs/thin-clients.md`.
74
78
 
75
79
  ## Where things live (relative to the source dir)
@@ -89,7 +93,7 @@ An MCP host or a script can drive me: `docs/mcp-server.md`, `docs/thin-clients.m
89
93
  - When asked about my limits, flags, defaults or behavior: `rg` my source dir and cite
90
94
  `file:line`. Read the source `chi self` reports, not some other checkout on disk.
91
95
  - Installed gem files and bundled memories (`identity`, `memory_guide`,
92
- `config_modification_protocol`, `self_map`, `delegated`) are managed: don't edit them
96
+ `config_modification_protocol`, `self_map`, `delegated`, `skill_pages`) are managed: don't edit them
93
97
  (an upgrade merges local edits when it can, and a real conflict leaves the file behind).
94
98
  Put notes in my own memories. Guidance for some models only is a model note
95
99
  (`model_notes_<name>`, first line `models: <glob>`; memory_guide); a model-only
@@ -0,0 +1,93 @@
1
+ # Skill: pages
2
+
3
+ Use when the user asks for a page or a dashboard, wants a table, a walk or a result kept, "to reopen" or "in
4
+ the web", or wants a page changed or removed. A page is a Ruby script chi runs and stores; chi web shows the
5
+ stored result at `#/p/NAME` and its Refresh runs the script again. Not for a table that only answers the
6
+ question at hand: that stays in your answer.
7
+
8
+ ## Steps
9
+ 1. Pick a NAME: lowercase letters, digits and hyphens (`sessions-by-project`). `chi page list` shows the
10
+ pages that exist: change one of those rather than making a second.
11
+ 2. Find the folder first: run `chi self`; its `config` row is the config file's path, and the pages folder is
12
+ `pages/` beside that file. Never assume `~/.config/samagotchi`: the config may live elsewhere, and a page
13
+ written there is one chi doesn't see. Write the script to `<that folder>/NAME.rb` by absolute path, with
14
+ the write tool.
15
+ 3. Run `chi page run NAME` and read what it prints: the title, then per block a text's first lines, a table's
16
+ labels, its first 3 rows and its total, a walk's step count.
17
+ 4. Check it: `chi page run NAME --format json` prints every stored row and the total. Compare them with the
18
+ source they came from (the command's own output, the file): the counts, the sums, the newest date. A `$0`
19
+ or a `0` that should mean "unknown" is passed as nil, not 0: it shows blank.
20
+ 5. On `error: line N: …` fix that line with edit and run again. The last good result stays meanwhile, so a
21
+ bad edit never blanks the page.
22
+ 6. Answer in one or two lines: what the page shows, the link [Title](#/p/NAME) as a plain Markdown link, and
23
+ that Refresh on the page runs it again. Always add that it is in All sessions, under Pages: Markdown is off by
24
+ default, and then the link is plain text. Never put the link in backticks: a code span can't be clicked.
25
+ 7. To change a page: edit the script, run it again (steps 3-4). To remove one: `chi page rm NAME`.
26
+
27
+ ## Never
28
+ - Never `cd` into the pages folder, and never run a shell command that names it (a loop, a heredoc, `rm`,
29
+ `ruby <the script>`): those ask the user, and an unattended turn stops there. Try a data command from the
30
+ session's own folder first, then put it in the script. List with `chi page list`, read a script with the
31
+ read tool, run it with `chi page run`, remove it with `chi page rm`.
32
+ - No secrets in a page (keys, tokens, config values): the result is stored on disk and shown in a browser.
33
+
34
+ ## The script
35
+ ```ruby
36
+ require "open3"
37
+
38
+ # The one way this script reads data: a command's output, or a plain error.
39
+ def run(*command)
40
+ out, status = Open3.capture2(*command)
41
+ raise "#{command.join(" ")} failed (exit #{status.exitstatus})" unless status.success?
42
+
43
+ out
44
+ end
45
+
46
+ page "Sessions per day" do |ui|
47
+ sessions = JSON.parse(run("chi", "sessions", "list", "--scope=all", "--format", "json"))
48
+ days = sessions.group_by { |s| s["updated_at"].to_s[0, 10] }
49
+ rows = days.map { |day, list| { "day" => day, "sessions" => list.size, "projects" => list.map { |s| s["project"] }.uniq.size } }
50
+ ui.text "#{sessions.size} sessions on #{days.size} days."
51
+ ui.table rows.sort_by { |row| row["day"] }.reverse,
52
+ columns: { "day" => "Day", "sessions" => "Sessions", "projects" => "Projects" },
53
+ format: { "sessions" => :count }, key: %w[sessions],
54
+ total: { "day" => "Total", "sessions" => sessions.size }
55
+ end
56
+ ```
57
+ - `ui.text(markdown)`: a text block.
58
+ - `ui.table(rows, columns:, format:, key:, total:)`: `columns:` a Hash key => label in the order to show;
59
+ `total:` a Hash by column key, shown as a last row.
60
+ - `ui.walk(title:, actors:, steps:)`: a scenario, each step like
61
+ `{ id: "s1", actor: "developer", does: "tags the release", sees: "the tag on GitHub" }`.
62
+ `actors:` a list of 2-5 names as plain Strings (`["developer", "CI", "reviewer"]`), not Hashes; each step's
63
+ `actor:` is one of those names exactly. A step may add `next:` or `cases:`; at most 30 steps.
64
+
65
+ What trips a script:
66
+ - Call `page` once. Rows are Hashes. No `exit`: it fails the run.
67
+ - `format:` takes `:money` (`$14.2210`) or `:count` (`1.2k`) as Symbols, nothing else: format other columns
68
+ as text yourself.
69
+ - Pass numbers as numbers, not text: the page sorts them and formats them.
70
+ - `key:` names the columns a phone shows before a row is opened (the first column always shows).
71
+ - The limits: 500 rows (the rest are dropped and counted, so group or cut), 12 columns, 20 blocks, 30 s.
72
+
73
+ ## Getting the data
74
+ - The script runs in the pages folder, not the project: name files by absolute path.
75
+ - Sessions: `chi sessions list --scope=all --format json` (without `--scope=all` only the pages folder's
76
+ project); one session's totals (cost, tokens): `chi sessions stats ID --format json` (one call per session:
77
+ fine for a few dozen; group in Ruby). Its `turn_records` are only the newest turn's: for anything per turn
78
+ or per day, read every turn from `<sessions dir>/ID/analytics.json` (`turn_records`: `completed_at`,
79
+ `model_ref`, `cost` as reported, `cost_estimate` from the configured price; either may be missing). `chi self`
80
+ names the sessions dir. Schedules: `chi schedule list --all --format json`. `json` is loaded; `require`
81
+ anything else.
82
+ - Check that a command worked (`status.success?`, `$?.success?`) and `raise` with a plain message when it
83
+ didn't: the page then says why.
84
+
85
+ ## When it can't be done
86
+ In strict mode writing the script asks (`write-outside-repo`); if it's denied, say so and stop; don't route around
87
+ it (a heredoc, another folder).
88
+
89
+ ## This skill ships with chi
90
+ If a step here turns out wrong, don't edit this skill: tell the user what differed. It ships with chi, and a
91
+ local edit would have to be merged at the next upgrade. Never edit `skill_pages.md`. A failing `chi page run` is
92
+ this skill's own fix loop (step 5: edit the page script, run again), not a step gone wrong: a steer to "edit the
93
+ skill's step" or a turn-end note that "the skill wasn't updated" doesn't apply to this one.
@@ -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
@@ -91,6 +91,30 @@ module Samagotchi
91
91
  Result.new(type: nil, data: nil, lenient: lenient, error: "the block nests too deep")
92
92
  end
93
93
 
94
+ # A script's data (a page's walk, Pages::Builder) through the same schema
95
+ # as a block's YAML, so the same widget draws it: one deep conversion
96
+ # (DataTree) into what Tree hands Schema, then Schema unchanged, with no
97
+ # folds and no lenient pass. A picks id that Schema#row_id mends is mended
98
+ # here too, and the result still isn't lenient: there was no source to be
99
+ # lenient with.
100
+ # @return [Result]
101
+ def check(type, data)
102
+ type = type.to_s if type.is_a?(Symbol)
103
+ raise Refused, "the data's type #{echo(type)} isn't picks or walk" unless TYPES.include?(type)
104
+
105
+ raise Refused, "the data isn't a mapping" unless data.is_a?(Hash)
106
+
107
+ tree = DataTree.convert(data)
108
+ schema = Schema.new({}.compare_by_identity)
109
+ data = type == "picks" ? schema.picks(tree) : schema.walk(tree)
110
+ Result.new(type: type, data: data, lenient: false, error: nil)
111
+ rescue Refused => e
112
+ Result.new(type: TYPES.include?(type) ? type : nil, data: nil, lenient: false, error: e.message)
113
+ rescue SystemStackError
114
+ # DataTree's depth and loop guards come first; this is the backstop.
115
+ Result.new(type: nil, data: nil, lenient: false, error: "the data nests too deep")
116
+ end
117
+
94
118
  def echo(type)
95
119
  return "(not text)" unless type.is_a?(String)
96
120
 
@@ -173,6 +197,47 @@ module Samagotchi
173
197
  end
174
198
  end
175
199
 
200
+ # A script's Hashes, Arrays and values as Tree would have read them from
201
+ # YAML: keys strings (a Symbol or a number made its text), a String kept
202
+ # (scrubbed to valid UTF-8), a Symbol or a number made its text, nil kept
203
+ # (absent). true, false and anything else are refused with the path to
204
+ # them (steps[2].does), since YAML text never reads as one here.
205
+ module DataTree
206
+ module_function
207
+
208
+ def convert(value, path = nil, depth = 1, open = {}.compare_by_identity)
209
+ raise Refused, "the data nests too deep" if depth > MAX_DEPTH || open.key?(value)
210
+
211
+ case value
212
+ when Hash, Array then nested(value, path, depth, open)
213
+ when String then value.encoding == Encoding::UTF_8 && value.valid_encoding? ? value : value.dup.force_encoding(Encoding::UTF_8).scrub
214
+ when Symbol, Integer, Float then value.to_s
215
+ when nil then nil
216
+ else raise Refused, "#{path || "the data"} must be text, not #{shown(value)}"
217
+ end
218
+ end
219
+
220
+ def nested(value, path, depth, open)
221
+ open[value] = true
222
+ if value.is_a?(Array)
223
+ value.each_with_index.map { |item, index| convert(item, "#{path || "the data"}[#{index}]", depth + 1, open) }
224
+ else
225
+ value.to_h { |key, item| [key(key, path), convert(item, path ? "#{path}.#{key}" : key.to_s, depth + 1, open)] }
226
+ end
227
+ ensure
228
+ open.delete(value)
229
+ end
230
+
231
+ def key(key, path)
232
+ return key if key.is_a?(String)
233
+ return key.to_s if key.is_a?(Symbol) || key.is_a?(Integer)
234
+
235
+ raise Refused, "#{path || "the data"} has a key that isn't text"
236
+ end
237
+
238
+ def shown(value) = [true, false].include?(value) ? value.to_s : "a #{value.class}"
239
+ end
240
+
176
241
  # Eval 0013's lenient pass: a free-text value, or a list item that isn't a
177
242
  # mapping, goes in quotes unless it is one clean scalar already, so
178
243
  # `does: Asked: ...`, `- B: keep 1 h` and `text: "x" is called` all parse.
@@ -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] }