samagotchi 0.184.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.
Files changed (119) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/docs/architecture.md +1 -1
  4. data/docs/bundles.md +62 -35
  5. data/docs/cli.md +10 -1
  6. data/docs/configuration.md +19 -1
  7. data/docs/context.md +76 -10
  8. data/docs/guardrails.md +20 -2
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/block-renderers.md +4 -2
  11. data/docs/internals/bridge.md +7 -2
  12. data/docs/internals/engine.md +15 -1
  13. data/docs/internals/llm-context-forget.md +6 -0
  14. data/docs/internals/participants.md +4 -1
  15. data/docs/internals/prompt-caching.md +14 -0
  16. data/docs/internals/remote-sessions.md +10 -1
  17. data/docs/internals/session-lifecycle.md +1 -1
  18. data/docs/internals/web-frontend.md +23 -6
  19. data/docs/mcp-server.md +6 -2
  20. data/docs/scheduling.md +5 -0
  21. data/docs/sessions.md +12 -2
  22. data/docs/sub-agent.md +48 -3
  23. data/docs/thin-clients.md +76 -4
  24. data/lib/samagotchi/agent_caller.rb +97 -0
  25. data/lib/samagotchi/bridge.rb +7 -7
  26. data/lib/samagotchi/bundles/claude-peer/manifest.yml +14 -8
  27. data/lib/samagotchi/bundles/claude-peer/plugin.rb +3 -3
  28. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +49 -30
  29. data/lib/samagotchi/bundles/claude-peer/scripts/pair +2 -2
  30. data/lib/samagotchi/bundles/claude-peer/scripts/pair-remote +123 -0
  31. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +11 -3
  32. data/lib/samagotchi/bundles/codex-peer/manifest.yml +10 -8
  33. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  34. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +29 -8
  35. data/lib/samagotchi/bundles/codex-peer/scripts/pair +1 -1
  36. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +11 -3
  37. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  38. data/lib/samagotchi/bundles/mcp/http_client.rb +19 -2
  39. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  40. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  41. data/lib/samagotchi/bundles/system/self_map.md +2 -0
  42. data/lib/samagotchi/client_id.rb +61 -1
  43. data/lib/samagotchi/command_intake.rb +16 -8
  44. data/lib/samagotchi/config.rb +3 -1
  45. data/lib/samagotchi/context_absorber.rb +215 -46
  46. data/lib/samagotchi/delivery.rb +15 -0
  47. data/lib/samagotchi/driver_command.rb +68 -0
  48. data/lib/samagotchi/engine/block_fix.rb +2 -2
  49. data/lib/samagotchi/engine.rb +20 -5
  50. data/lib/samagotchi/engine_peers.rb +6 -0
  51. data/lib/samagotchi/guardrails/pair_boundary.rb +1 -1
  52. data/lib/samagotchi/llm/chat_loop.rb +16 -2
  53. data/lib/samagotchi/mcp_command.rb +7 -2
  54. data/lib/samagotchi/mcp_server/tools.rb +9 -3
  55. data/lib/samagotchi/objectives_track.rb +2 -1
  56. data/lib/samagotchi/owner_prompt.rb +5 -1
  57. data/lib/samagotchi/parent_report.rb +9 -5
  58. data/lib/samagotchi/plain_reply.rb +75 -0
  59. data/lib/samagotchi/plugin/peer.rb +10 -4
  60. data/lib/samagotchi/reply_for.rb +254 -0
  61. data/lib/samagotchi/reply_wait.rb +12 -3
  62. data/lib/samagotchi/schedules.rb +10 -7
  63. data/lib/samagotchi/send_command/parent_gate.rb +3 -1
  64. data/lib/samagotchi/send_command.rb +45 -8
  65. data/lib/samagotchi/session.rb +9 -1
  66. data/lib/samagotchi/session_access/ask.rb +10 -4
  67. data/lib/samagotchi/session_access/contract.rb +2 -0
  68. data/lib/samagotchi/session_access/exchange/token.rb +42 -7
  69. data/lib/samagotchi/session_access/exchange.rb +5 -2
  70. data/lib/samagotchi/session_access/local.rb +6 -3
  71. data/lib/samagotchi/session_access/remote.rb +23 -3
  72. data/lib/samagotchi/session_access.rb +4 -2
  73. data/lib/samagotchi/session_command_catalog.rb +8 -0
  74. data/lib/samagotchi/session_commands.rb +9 -0
  75. data/lib/samagotchi/session_continue.rb +4 -1
  76. data/lib/samagotchi/session_inbox.rb +2 -0
  77. data/lib/samagotchi/session_inbox_delivery.rb +4 -2
  78. data/lib/samagotchi/session_manager/delivery.rb +80 -5
  79. data/lib/samagotchi/session_manager/spawn.rb +7 -1
  80. data/lib/samagotchi/steer.rb +119 -22
  81. data/lib/samagotchi/terminal_ui/formatting.rb +12 -2
  82. data/lib/samagotchi/tool_activity.rb +4 -0
  83. data/lib/samagotchi/tool_declarations.rb +22 -1
  84. data/lib/samagotchi/tool_names.rb +4 -0
  85. data/lib/samagotchi/toolkit.rb +3 -2
  86. data/lib/samagotchi/tools/ask_session.rb +208 -0
  87. data/lib/samagotchi/tools/builtin_calls.rb +1 -0
  88. data/lib/samagotchi/tools/builtins.rb +5 -0
  89. data/lib/samagotchi/turn_anchors.rb +65 -17
  90. data/lib/samagotchi/turn_checkpoint.rb +21 -2
  91. data/lib/samagotchi/turn_stages/context_judge.rb +3 -1
  92. data/lib/samagotchi/turn_stages/objectives.rb +4 -2
  93. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +3 -0
  94. data/lib/samagotchi/version.rb +1 -1
  95. data/lib/samagotchi/visitor.rb +37 -0
  96. data/lib/samagotchi/web/app.rb +1 -1
  97. data/lib/samagotchi/web/ask_routes.rb +68 -21
  98. data/lib/samagotchi/web/message_display.rb +15 -2
  99. data/lib/samagotchi/web/participant_access.rb +1 -1
  100. data/lib/samagotchi/web/public/app.js +1 -1
  101. data/lib/samagotchi/web/public/block_fix.js +11 -3
  102. data/lib/samagotchi/web/public/history_shape.js +3 -1
  103. data/lib/samagotchi/web/public/index.html +8 -0
  104. data/lib/samagotchi/web/public/peer_links.js +27 -4
  105. data/lib/samagotchi/web/public/peer_note.js +19 -3
  106. data/lib/samagotchi/web/public/peer_text.js +62 -0
  107. data/lib/samagotchi/web/public/picture_regions.js +2 -2
  108. data/lib/samagotchi/web/public/turn_events.js +19 -0
  109. data/lib/samagotchi/web/public/working_set_view.js +11 -2
  110. data/lib/samagotchi/web/session_access_routes.rb +30 -2
  111. data/lib/samagotchi/web/session_control.rb +22 -3
  112. data/lib/samagotchi/web/session_create.rb +11 -7
  113. data/lib/samagotchi/worker/command_queue.rb +5 -2
  114. data/lib/samagotchi/worker/senders.rb +79 -0
  115. data/lib/samagotchi/worker.rb +22 -18
  116. data/lib/samagotchi/worker_inbound.rb +12 -4
  117. data/lib/samagotchi/worker_participant_gate.rb +1 -3
  118. data/lib/samagotchi/worker_wakes.rb +12 -0
  119. metadata +10 -1
@@ -839,7 +839,10 @@ means the owner: a turn or session with no author keys reads as the owner's and
839
839
  when nothing is left), so a name can't close it. The header always comes first, so text under it stays the
840
840
  participant's. A line of their text that opens like one of chi's headers (a review contribution, a steer, automatic
841
841
  input, a delegate report) goes out led by `(quoted) ` (`Steer.quote_forged_headers`, wire-only and deterministic),
842
- so it reads as their text under the real header. The session file never holds the header or the quote mark.
842
+ so it reads as their text under the real header. A line starts after any break a model reads as one
843
+ (`Steer::FORGED_BREAKS`), and spaces, format characters and markdown leads may come before the bracket
844
+ (`Steer::FORGED_LEAD`, the one shape `Steer.forged_frames` builds for every forged-frame match). Widening that
845
+ shape changed the wire bytes once for an older text with such a line (a one-time cache miss on its replay). The session file never holds the header or the quote mark.
843
846
  - **The system-prompt line.** While the session has an active participant (`participants.json`, read by the
844
847
  worker's Engine at each turn's start), the system prompt's volatile tail opens with "Participants: teammates the
845
848
  owner invited work in this session too. …" (`SystemPrompt::PARTICIPANTS_LINE`), which names the pair header (and the
@@ -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
@@ -297,7 +304,9 @@ with a "Machine-local" comment; the rest branch on `@access.remote?` (`SendComma
297
304
  `cross_site?` lets CLI clients through because they send no `Origin` or `Sec-Fetch-Site`.
298
305
  - **`client_id` only tightens.** `handle_question_answer` (`Web::SessionControl`) forwards `client_id` only when it is `ClientId::CLI_ANSWER`
299
306
  and drops any other value, so a remote answer is held to the parent rules and can't pass for the user's own. On
300
- create and turn, a `cli:send` / `cli:answer` id adds checks (`CLI_SEND_IDS`) and never removes any.
307
+ create and turn, a `cli:send` / `cli:answer` / `agent:` id adds checks (`ClientId.parent_line?`) and never removes
308
+ any. An agent's id goes to a chi web without `agent_sender` in its `/api/info` features as `cli:send`
309
+ (`Remote#sent_id`, compat shim agent_client_id), for a turn and a create.
301
310
  - **A remote attach's `client_id`** (`tui:<pid>@<host>`, P4-D6) is forwarded as given on `/turn` and `/command`, as
302
311
  the page's is: the token is the owner. Only the cli ids (`cli:send`, `cli:answer`) add checks there; a parent
303
312
  agent driving the TUI from a pipe answers as `cli:answer`, held to that machine's `guardrails.parent_answers`.
@@ -74,7 +74,7 @@ state. A cell is `:go`, `:wait` or the decider's own refusal reason; `SessionLif
74
74
  `:go`, `:wait` or `:refused` (resume's `live` and `starting` wait, restart's `fallback` goes).
75
75
 
76
76
  - **Delivery columns** (send, note, push, ring, fresh_verdict, leave, schedule, plugin, delegate, participant,
77
- automatic) are generated at load from `SessionInbox::WakePolicy::ROWS`, unchanged: each row's `decide` on
77
+ agent, automatic) are generated at load from `SessionInbox::WakePolicy::ROWS`, unchanged: each row's `decide` on
78
78
  `CANONICAL[state]` (a worker asked for, no scratch file), `:start`/`:live` as go, `:starting`/`:stopped`/
79
79
  `:archived`/`:none` as wait, `:gone`/`:owned`/`:deleting` as themselves. `:off` and `:scratch` are op-local.
80
80
  `deleting` refuses every kind: `WakePolicy#refusal` before the write (nothing written), `#decide` after it (a
@@ -37,7 +37,7 @@ sheet still keeps `isChained` and `format.js deleteConfirmText` that way; and `w
37
37
  with 0.183.0's `ws_reader.js` and `ws_peek.js`, and 0.183.0's view with this `ws_reader.js`, from
38
38
  `spec/web/public/fixtures/v0.183.0/`). `answer_fold.js`, `details_motion.js`,
39
39
  `turn_range.js`, `history_reveal.js`, `latest.js`, `session_payload.js`, `method_api.js`, `session_store.js`,
40
- `session_fields.js`, `feature_gates.js`, `revise_stack.js`, `revise_switch.js`, `shell_command.js`, `stale_params.js`, `popover_modal.js`, `more_sheet.js`, `delete_sheet.js` (The delete sheet, below), `removal_sheet_model.js` (its words: rows, button words, the archive model, the toast; DOM-free), `running_tasks.js` (a delete's or archive's tasks: their line and the toast's suffix; DOM-free, so `stop_sheet.js` and the delete sheet share its cut), `hash_intent.js` (what the hash asks for: session, all, start or keep), `worker_features.js`, `version_notices.js`, `owner_claim.js`, `owner_verify.js`, `composer_mode.js`, `strip_hidden.js`, `block_open.js`, `text_roots.js`, `block_source.js`, `block_frame.js`, `block_host.js`, `block_watch.js`, `card_stamps.js`, `recap_stamp.js` (a saved recap's place by its `opening_id` stamp, else its count), `inline_widgets.js`, `widget_walk.js`, `widget_picks.js`, `history_shape.js` (the history's shape, live against a reload: the e2e reload checks and the opt-in reload check share its normalizer and its `ACCEPTED` allowlist), `turn_pieces.js` (a finished turn's one order and its answer rule: the live hand-off's `handOffOrder` and `turnEnded`, and a reload's `turnHistoryNodes`), `reload_check.js` (the opt-in `web.reload_check`: after the stage's hand-off, the turn against a reload of it, the counts posted; the history without its cards and questions, and those as data: the page's `card_registry.js` against one seeded from the read, this turn's entries, a capped read's missing keys skipped), `turn_drawing.js` (a finished turn's drawing, `turn_drawings` in the show: its fold into steps and its end kind; `turn_block.js` draws it), `stage_stall.js` (the stage's quiet signal), `stage_quiet_clock.js`, `stage_dom.js`, `stage_answer.js`, `stage_pager.js`, `stage_cloud.js`, `stage_handoff.js`, `stage_place.js`, `stage_probe.js` (the stage's features: below, The stage's modules), `card_kinds.js` (what a card waits as, from its data: the kind, approval and folded-row text the stage's registry takes; the node's read is its cross-check), `card_registry.js` (the open session's cards as data, an observer of the stream's card events and a read's seed: Where state lives), `history_end.js` (the stage's one move of pieces to the history's end), `stage_opened.js` (a running turn opened in the history while a card waits: the lead-in bubble, the moves, the end fold), `stage_asking.js` (the stage's docked card and its fold: the docking and lead-in rules, the opening, a waiting card's own toggle, the folded row's text per kind, the fold's choice, reveal and the docked card's fold; `stage_view.js` wires it), `stage_waiting.js` (the stage's waiting cards as data, keyed by `data-qid` / `data-card-id`: kind, docked, approval, the stage's order, the shown card and its pager, the docked card's fold, kept for this tab in `chi_asking_fold:<session>`; `front`, `count`, `shown`, `blocking`), `stage_cards.js` (the cards that wait in the stage: `PENDING`, `ASKS`, `waitsInStage`, read by `stage_model.js placeKind`), `resync_reach.js` (a re-read that can't reach chi web keeps the drawn history; the status chip says retrying / offline, outside a turn), `session_sync.js` (the open session's sync: `select`, `resync` and its retries, the stream's life; the stream handle and the re-read bookkeeping are its own), `session_view.js` (the open session's view: `renderSessionView` draws a read, `forgetSession` resets the page for another session, `readTurnEnd`, `endTurnView`; app.js makes both right after the cards, each reaching the other and the later views through getters), `participant_main.js`, `participant_bar.js`, `viewer_self.js`, `participant_history.js` (a participant's ↑/↓ list), `stage_owner_wait.js`, `participant_revise.js` (a participant's page: The participant's page, below), `ws_timeline.js`, `ws_cards.js`, `ws_peek.js`, `ws_part_peek.js`, `ws_reader.js`, `ws_way_in.js`, `ws_item_sig.js`, `ws_markdown.js` (what chi has of a working-set item: below, The working set's reader), `session_prefs.js` (a session's own view settings, `<key>:<session>`: Storage keys, below), `ws_sections.js` (the working set's head view: its sections from the prompt's parts, [working-set.md](working-set.md), The head view), `ws_order.js` (the working-set list's order: last touched first, held while it is open, [working-set.md](working-set.md), The list's order), `ctx_tokens.js` (the context's token count beside its %: `ctxTokens`, below), `stage_view_memory.js` (what was opened of a running turn, per session, in memory: Where state lives), `peer_data.js`, `peer_exchange.js`, `peer_note.js`, `peer_links.js` (a peer's send and answer in the conversation: The peer exchange, below), `peer_chip.js` (a paired peer's one chip in the session bar: The peer exchange), `picture_viewer.js` (the picture viewer, `#lightbox`: below, Picture viewer), `pan_zoom.js` (its maths, pure), `diagram_wiring.js` (`wireDiagrams`: the block host with the viewer as its `openPicture`, the viewer closed on a theme change, the regions' layer given to the viewer; the viewer itself stays made in app.js, which `createSessionView` reads first), `block_regions.js` (a renderer's regions cleaned, pure: [block-renderers.md](block-renderers.md#regions)), `region_hit.js` (their hit test, the arrow keys' nearest region and the reveal under the card, pure), `picture_regions.js` (the regions' layer over the viewer: below, Picture viewer), `no_contact_fill.js` (a text field that isn't a contact form: autocomplete off and a name with no contact word, against iOS Safari's AutoFill Contact bar; a template's fields carry the same attributes, and its spec checks the page's markup for them) and the `objectives_*.js` modules are new modules for that reason. The last four `block_*` draw fenced blocks (`block_watch.js` finds and watches them, `block_host.js` is its frame drawer for a bundle's renderers): [block-renderers.md](block-renderers.md). `inline_widgets.js` is its core drawer for `chi-ui` blocks, drawing `widget_walk.js`'s and `widget_picks.js`'s widgets in a shadow root styled by `widgets.css`: [inline-widgets.md](inline-widgets.md).
40
+ `session_fields.js`, `feature_gates.js`, `revise_stack.js`, `revise_switch.js`, `shell_command.js`, `stale_params.js`, `popover_modal.js`, `more_sheet.js`, `delete_sheet.js` (The delete sheet, below), `removal_sheet_model.js` (its words: rows, button words, the archive model, the toast; DOM-free), `running_tasks.js` (a delete's or archive's tasks: their line and the toast's suffix; DOM-free, so `stop_sheet.js` and the delete sheet share its cut), `hash_intent.js` (what the hash asks for: session, all, start or keep), `worker_features.js`, `version_notices.js`, `owner_claim.js`, `owner_verify.js`, `composer_mode.js`, `strip_hidden.js`, `block_open.js`, `text_roots.js`, `block_source.js`, `block_frame.js`, `block_host.js`, `block_watch.js`, `card_stamps.js`, `recap_stamp.js` (a saved recap's place by its `opening_id` stamp, else its count), `inline_widgets.js`, `widget_walk.js`, `widget_picks.js`, `history_shape.js` (the history's shape, live against a reload: the e2e reload checks and the opt-in reload check share its normalizer and its `ACCEPTED` allowlist), `turn_pieces.js` (a finished turn's one order and its answer rule: the live hand-off's `handOffOrder` and `turnEnded`, and a reload's `turnHistoryNodes`), `reload_check.js` (the opt-in `web.reload_check`: after the stage's hand-off, the turn against a reload of it, the counts posted; the history without its cards and questions, and those as data: the page's `card_registry.js` against one seeded from the read, this turn's entries, a capped read's missing keys skipped), `turn_drawing.js` (a finished turn's drawing, `turn_drawings` in the show: its fold into steps and its end kind; `turn_block.js` draws it), `stage_stall.js` (the stage's quiet signal), `stage_quiet_clock.js`, `stage_dom.js`, `stage_answer.js`, `stage_pager.js`, `stage_cloud.js`, `stage_handoff.js`, `stage_place.js`, `stage_probe.js` (the stage's features: below, The stage's modules), `card_kinds.js` (what a card waits as, from its data: the kind, approval and folded-row text the stage's registry takes; the node's read is its cross-check), `card_registry.js` (the open session's cards as data, an observer of the stream's card events and a read's seed: Where state lives), `history_end.js` (the stage's one move of pieces to the history's end), `stage_opened.js` (a running turn opened in the history while a card waits: the lead-in bubble, the moves, the end fold), `stage_asking.js` (the stage's docked card and its fold: the docking and lead-in rules, the opening, a waiting card's own toggle, the folded row's text per kind, the fold's choice, reveal and the docked card's fold; `stage_view.js` wires it), `stage_waiting.js` (the stage's waiting cards as data, keyed by `data-qid` / `data-card-id`: kind, docked, approval, the stage's order, the shown card and its pager, the docked card's fold, kept for this tab in `chi_asking_fold:<session>`; `front`, `count`, `shown`, `blocking`), `stage_cards.js` (the cards that wait in the stage: `PENDING`, `ASKS`, `waitsInStage`, read by `stage_model.js placeKind`), `resync_reach.js` (a re-read that can't reach chi web keeps the drawn history; the status chip says retrying / offline, outside a turn), `session_sync.js` (the open session's sync: `select`, `resync` and its retries, the stream's life; the stream handle and the re-read bookkeeping are its own), `session_view.js` (the open session's view: `renderSessionView` draws a read, `forgetSession` resets the page for another session, `readTurnEnd`, `endTurnView`; app.js makes both right after the cards, each reaching the other and the later views through getters), `participant_main.js`, `participant_bar.js`, `viewer_self.js`, `participant_history.js` (a participant's ↑/↓ list), `stage_owner_wait.js`, `participant_revise.js` (a participant's page: The participant's page, below), `ws_timeline.js`, `ws_cards.js`, `ws_peek.js`, `ws_part_peek.js`, `ws_reader.js`, `ws_way_in.js`, `ws_item_sig.js`, `ws_markdown.js` (what chi has of a working-set item: below, The working set's reader), `session_prefs.js` (a session's own view settings, `<key>:<session>`: Storage keys, below), `ws_sections.js` (the working set's head view: its sections from the prompt's parts, [working-set.md](working-set.md), The head view), `ws_order.js` (the working-set list's order: last touched first, held while it is open, [working-set.md](working-set.md), The list's order), `ctx_tokens.js` (the context's token count beside its %: `ctxTokens`, below), `stage_view_memory.js` (what was opened of a running turn, per session, in memory: Where state lives), `peer_data.js`, `peer_exchange.js`, `peer_note.js`, `peer_links.js`, `peer_text.js` (a peer's send and answer in the conversation: The peer exchange, below), `peer_chip.js` (a paired peer's one chip in the session bar: The peer exchange), `picture_viewer.js` (the picture viewer, `#lightbox`: below, Picture viewer), `pan_zoom.js` (its maths, pure), `diagram_wiring.js` (`wireDiagrams`: the block host with the viewer as its `openPicture`, the viewer closed on a theme change, the regions' layer given to the viewer; the viewer itself stays made in app.js, which `createSessionView` reads first), `block_regions.js` (a renderer's regions cleaned, pure: [block-renderers.md](block-renderers.md#regions)), `region_hit.js` (their hit test, the arrow keys' nearest region and the reveal under the card, pure), `picture_regions.js` (the regions' layer over the viewer: below, Picture viewer), `no_contact_fill.js` (a text field that isn't a contact form: autocomplete off and a name with no contact word, against iOS Safari's AutoFill Contact bar; a template's fields carry the same attributes, and its spec checks the page's markup for them) and the `objectives_*.js` modules are new modules for that reason. The last four `block_*` draw fenced blocks (`block_watch.js` finds and watches them, `block_host.js` is its frame drawer for a bundle's renderers): [block-renderers.md](block-renderers.md). `inline_widgets.js` is its core drawer for `chi-ui` blocks, drawing `widget_walk.js`'s and `widget_picks.js`'s widgets in a shadow root styled by `widgets.css`: [inline-widgets.md](inline-widgets.md).
41
41
 
42
42
  ## One page, every viewer
43
43
 
@@ -545,8 +545,10 @@ how it went); only the redraw is counted: an answer is read again at most once p
545
545
  (the route's 200 `fixed` or the event's), and a block failing after it says a fix didn't help. The stream's `block_fix` handler
546
546
  (`stream_handlers.js`, dep `blockFix`) hands the worker's word over: `fixed` re-reads that turn's answer (`getSession(id,
547
547
  {tail, turnId})`) and writes the bubble as `applyFinalAnswer` writes it, which can't find it by its old text; `failed`
548
- and `dropped` say a fix didn't help. A block is marked asked (`data-block-fix-asked`) before its POST, since the word can
549
- come before the 202 (a quick side answer); a 202 after it starts no give-up. No word within 60 s of a 202: the line
548
+ and `dropped` say a fix didn't help. Both 202 answers carry the block's key (`data-block-fix-key`); a keyed event settles
549
+ only that asked block, leaving another block's give-up timer running. A block is marked asked before its POST, since the
550
+ word can come before the 202 (a quick side answer); an event before the 202 or an older worker's keyless 202 keeps the
551
+ all-asked fallback for unkeyed blocks. A 202 after the word starts no give-up. No word within 60 s of a 202: the line
550
552
  gives up (today's words and Ask in chat);
551
553
  a session switch drops the timers. The line's words are `data-text` (CSS), Ask in chat a button whose label is CSS
552
554
  (`data-label`) with an `aria-label`, one delegated click listener per root; it fills the composer after the draft
@@ -838,7 +840,8 @@ conversation ([bundles.md](../bundles.md#the-claude-peer-bundle), In the web). T
838
840
  `peer_exchanges.jsonl`, the peers from its pushed sources) gives each peer's last exchanges, newest first, with their
839
841
  `state` (waiting, answered, none_expected, failed) and an answer's `serial` and `verdict`; a send row carries the
840
842
  send's id as its `peer` ref, a peer's answer note its `peer` hash (`peer`, `label`, `re`, `summary`, `serial`,
841
- `verdict`, `agreed`). The page joins and parses nothing.
843
+ `verdict`, `agreed`, and `inline` when the note's content holds the peer's text). The page joins nothing; the one
844
+ parse is `peer_text.js`'s cut of an `inline` note's text block.
842
845
 
843
846
  - `peer_data.js` (state): `listPeers` (an older chi web's 404 is an empty list) and `createPeers`, the page's one model
844
847
  of the open session's peers (app.js `peers`, made only with the `context` capability, so a participant's page has
@@ -856,7 +859,17 @@ send's id as its `peer` ref, a peer's answer note its `peer` hash (`peer`, `labe
856
859
  - `peer_note.js`: `peerNoteTemplate`, which `turn_html.js noteBubbleTemplate` draws a note with `peer` as. It keeps
857
860
  what an opening note has (`bubble note`, `turn-start`, `data-opening-id`, the time title), so `TURN_PROMPT`,
858
861
  `card_stamps.js`, `stage_handoff.js OPENING`, `reload_check.js` and `revise_stack.js` (its `.note-text` is the
859
- summary) read it as any wake note.
862
+ summary) read it as any wake note. With `peer.inline` the peer's text goes in `.peer-text` under the summary (an
863
+ element of its own, not a `data-peer-slot`, its source in `data-peer-md`): already as markdown when a history
864
+ read sent the note's `peer_html` (`MessageDisplay#peer_text_html`, `ContextAbsorber.peer_text_of`, rendered and
865
+ sanitized as an answer is), else as plain text (a live `context_added`, an older server), the "what chi told the
866
+ agent" fold shows the content without the block, and the bubble carries `data-peer-inline`. Without it (an older
867
+ session, an answer over the cap) the bubble draws as before.
868
+ - `peer_text.js` (pure): `peerBlock(content)` cuts the text out between the first `[PEER MESSAGE from …]` line and the
869
+ last `[END PEER MESSAGE]` line and undoes the absorber's `(quoted) ` mark on forged frame lines
870
+ (`PEER_FORGED_OPENINGS` and `PEER_FORGED_LINES`, the Ruby `ContextAbsorber`'s, and the same line breaks and leads
871
+ as `Steer::FORGED_BREAKS` / `FORGED_LEAD`: `peer_text.test.js` keeps the lists alike and undoes the Ruby specs' cases);
872
+ null without a block.
860
873
  - **The slot idiom.** Finished rows are never drawn again and a reload makes them anew, so what arrives later is
861
874
  drawn into empty slots the templates leave: a send row's `<span class="peer-slot" data-peer-ref>` after its params
862
875
  (`turn_html.js toolRowInnerTemplate`; the row's output line isn't drawn on a send that didn't fail, its text the
@@ -867,7 +880,11 @@ send's id as its `peer` ref, a peer's answer note its `peer` hash (`peer`, `labe
867
880
  sent" when its row failed, or once its turn has ended when its peer's list is under the server's cap of 20
868
881
  (`EXCHANGES_CAP`) or holds a send drawn before it; else it is unknown and gets no pill, as are the sends of a peer
869
882
  the read doesn't name), the ↑ into each answer (none for an answer no send claims) and "Read the full
870
- answer" into the last answer of each source only. Its one delegated click handler on the turn roots does the jumps,
883
+ answer" into the last answer of each source only, unless that bubble is `data-peer-inline` (its text is there). It
884
+ also swaps a plain inline bubble's `.peer-text` (not `.markdown`: one that came with `peer_html` asks nothing) for
885
+ its markdown (`renderMarkdown`, POST /api/render, sanitized there; an
886
+ optional factory dep, so a cached older app.js leaves the text plain), once per element; `history_shape.js` reads a
887
+ `[data-peer-md]` element as its source, so live and an offscreen reload compare alike. Its one delegated click handler on the turn roots does the jumps,
871
888
  buttons, never an `href` (the page routes by its hash): ↓ `revealInHistory` + `scrollIntoView` on the answer; ↑
872
889
  `refs.js showRow` on the last row of that id before the answer (its `ref:reveal` opens a folded step or the stage's
873
890
  cloud); focus moves to the target (`tabindex="-1"`). "Read the full answer" calls `context_chips.js showText(name)`,
data/docs/mcp-server.md CHANGED
@@ -67,10 +67,14 @@ with `isError: true` and chi's own words; only an unknown tool is a protocol err
67
67
  ## Who the caller is
68
68
 
69
69
  The host is an agent driving a session, as `chi send --wait` and `chi answer` are (see [chi as a
70
- sub-agent](sub-agent.md)): its messages go in as `chi send`'s, its answers and a `/continue yes` as `chi answer`'s.
70
+ sub-agent](sub-agent.md)): its messages go in as an agent's, its answers and a `/continue yes` as `chi answer`'s.
71
71
  So `guardrails.parent_answers` holds it (see [Guardrails](guardrails.md#answers-from-a-parent-agent)): what it may
72
72
  pick on an approval or a step-limit question, and whether it may continue a turn that ran out of iterations. The
73
- page shows its turns with the "chi send" label.
73
+ page shows its turns as an agent's: on stdio (`chi mcp serve`) named by the host's marker in its environment
74
+ (`CLAUDECODE` gives "agent claude", see [driver and visitor](sub-agent.md#an-agents-messages-driver-and-visitor)),
75
+ else "agent mcp"; over HTTP (`POST /api/mcp`) always "agent mcp". Whether Claude Code exports `CLAUDECODE` to the
76
+ stdio servers it starts is up to Claude Code: without it the host is "agent mcp". A session the host didn't create
77
+ takes its messages as a visitor's (one header line, counted toward `session.max_wakes`).
74
78
 
75
79
  `chi_ask` takes a message for the model, not a command: a line starting with `!` (a shell line) or with `/` (a
76
80
  session command; `/continue …` is the one exception) is refused. That is narrower than `chi send` on purpose: a
data/docs/scheduling.md CHANGED
@@ -197,6 +197,11 @@ tick is about an hour of patience, which is what the count really measures.
197
197
  `chi schedule enable` resets both counters too: a schedule turned back on gets its
198
198
  whole budget again, not one skip.
199
199
 
200
+ A recurring schedule the owner has disabled stays off when an in-flight skip or
201
+ failure is recorded. A `date` one-off is the exception: a skip or failure puts its
202
+ moment back and re-enables it. `run-now` still tries a disabled schedule, but a
203
+ refusal records its result without moving the skip or failure counters.
204
+
200
205
  The tick line that disabled an entry ends `(disabled)` (`chi schedule tick`,
201
206
  `run-now`), and `tick --format json` gives that outcome `"disabled": true`
202
207
  (`Schedules::Outcome#disabled`). When **chi web's** tick (`schedule.auto_tick`)
data/docs/sessions.md CHANGED
@@ -39,7 +39,7 @@ Retention and manual prune/clean silently stop each deleted session's verified b
39
39
 
40
40
  **Always attached:** every interactive `chi` (plain, `-p`, `--resume ID`, `--attach ID`, `chi scratch`) runs its session in a background worker and attaches to it; there is no setting for it. The worker runs in the session's `working_directory`, so `!commands` and tools see the directory the session was started in. Only `chi -p TEXT --non-interactive` runs its one turn in this process; while it does, the session can't be attached ("in use by a one-turn chi --non-interactive run or an older chi's terminal"). See [CLI: Sharing a session](cli.md#sharing-a-session).
41
41
 
42
- **Who may wake a session:** every turn delivery names its sender (`SessionManager.deliver_turn` requires `client_id`), and the sender's kind picks what it may do to the worker (`ClientId.wake_kind`, `SessionInbox::WakePolicy.for_sender`). A person — `chi send`, a web tab, an attached terminal — starts an idle session, un-stops a stopped one and brings back an archived link. Nobody's message goes into a session being deleted (409 `session_deleting`, *Deleting a session* above). A schedule's firing, a plugin's `ctx.sessions.send`, a `delegate` follow-up, a participant's turn and any sender chi doesn't name start an idle session only: a session its owner stopped or archived refuses them (409 `session_stopped`, "the session is stopped; only its owner's message starts it again", or `session_archived`, "…brings it back"), nothing written. A schedule counts that as a skip (and skips a stopped session at its check, [scheduling.md](scheduling.md)); `delegate` says it as `Error: session <id8> refused: …`; a plugin gets `Error`. A turn already handed to a live worker is that worker's, as before. chi web's owner turn and command routes name a body that carries no `client_id` as `web:unnamed` (a web tab's rights).
42
+ **Who may wake a session:** every turn delivery names its sender (`SessionManager.deliver_turn` requires `client_id`), and the sender's kind picks what it may do to the worker (`ClientId.wake_kind`, `SessionInbox::WakePolicy.for_sender`). A person — `chi send`, a web tab, an attached terminal — starts an idle session, un-stops a stopped one and brings back an archived link. Nobody's message goes into a session being deleted (409 `session_deleting`, *Deleting a session* above). A schedule's firing, a plugin's `ctx.sessions.send`, a `delegate` follow-up, a participant's turn, an agent's `chi send` (`agent:<name>`, [driver and visitor](sub-agent.md#an-agents-messages-driver-and-visitor)), another session's `ask_session` and any sender chi doesn't name start an idle session only: a session its owner stopped or archived refuses them (409 `session_stopped`, "the session is stopped; only its owner's message starts it again", or `session_archived`, "…brings it back"), nothing written. A schedule counts that as a skip (and skips a stopped session at its check, [scheduling.md](scheduling.md)); `delegate` says it as `Error: session <id8> refused: …`; a plugin gets `Error`. A turn already handed to a live worker is that worker's, as before. chi web's owner turn and command routes name a body that carries no `client_id` as `web:unnamed` (a web tab's rights).
43
43
 
44
44
  **Which chi a worker runs:** a new or woken worker runs the newest chi installed for this Ruby (`gem 'samagotchi', '>= 0.a'`, prereleases count), whoever starts it: a `chi web` or terminal still on an older chi starts it on the newest one, so a stale process doesn't spread old code. A worker already running keeps its version until it is restarted. Should the newest install fail to load, the worker runs the starter's own version and logs `boot_fallback` (its stdio is `/dev/null`). Under `bundle exec` the worker drops Bundler's env first, so it activates the newest gem too. Two consequences: a wrapper pin (`chi _0.17.0_ web`) pins only that process, not the workers it starts; and a source checkout (`bin/chi` in a worktree, `bundle exec`) starts its workers on its own `lib/`, but a session it made that is later woken by an installed chi (`chi web`, `chi send`) runs the installed code. The names an older starter hands a newer worker (the boot line, its env keys, `input/` files, the session JSON fields and the Bridge routes sessions use on each other) are pinned in `spec/worker_contract_spec.rb`. A chi newer than 0.130.0 keeps the top-level keys it doesn't know (a newer chi's fields) when it saves a session, after its own, and doesn't act on them; `written_by` names the chi that saved the file last, and a worker woken on a file a newer chi saved logs `newer_writer`. chi 0.130.0 and older drop those keys: a session a newer chi made loses its newer fields when an older chi wakes or saves it (for example `chi --attach` from a project whose Ruby has an older chi). Keep the chi in every Ruby you run it from newer than 0.130.0.
45
45
 
@@ -175,6 +175,16 @@ chi sessions clean --dry-run --days 7 # test sessions older than 7 da
175
175
 
176
176
  A context note is text pushed into a session as background: not a prompt, and it starts no turn.
177
177
 
178
+ Its model's twin is `send_note` (a note to another session). To ask another session something and get its
179
+ answer back, the model has `ask_session` instead: `ask_session(session:, question:)` runs the question as a turn
180
+ of its own there (queued behind a running one), labelled `session <id8>` and read as `[Question from another chi
181
+ session (<id8>), asked by its model; not your user's message. …]`, a visitor's turn counted toward that session's
182
+ `session.max_wakes`. The answer is the tool's result; one call waits up to 35 s, then gives a token that
183
+ `ask_session(token:)` waits on. A session that waits on a question for its user is not answered (the asker says
184
+ so to its user). A stopped or archived session, one a one-turn run holds, a scratch session, the asker itself and a
185
+ `/` or `!` line are refused; a worker older than `ask_session` is refused too (restart it). It is in the toolkits
186
+ that hold `send_note` but a delegate child's, and not in a scratch session.
187
+
178
188
  ```sh
179
189
  chi note [--source NAME] [-m TEXT] (ID|PREFIX)... | --all
180
190
  pbpaste | chi note --source slack 3f2a 8c1d
@@ -327,7 +337,7 @@ pbpaste | chi send 3fa2 # the clipboard is the messa
327
337
  ```
328
338
 
329
339
  - With both stdin and `-m`, stdin is context: each line becomes a `> ` quote (as web annotations quote a selection), then a blank line, then the message. With only one, it goes in as is. A terminal on stdin is ignored. Both empty is a usage error; over 16 KiB is refused, never cut.
330
- - It goes through the same path as the web composer (`SessionManager.deliver_turn`): the worker's Bridge when it is up, so every attached UI shows it as your message (client id `cli:send`, shown like any user message); the input file when the worker is on its way out. During a running turn it is merged into that turn at the next step, like a message typed then, and cuts nothing. `--cut` asks for a cut, as `/cut TEXT` in a terminal does: a generation that has streamed only thinking for `steer.cut_after` seconds (per host/model: `steer_cut_after`) is cut (now, or once its thinking passes that), and the step starts again with the message. To an idle session `--cut` sends normally. `--cut --wait` into a running turn is refused like any `--wait` there (`busy: a turn is running`). `--queue` (not with `--cut`, a usage error) keeps the message for after the running turn: it runs as a turn of its own then (as `/queue TEXT` does), and a plain message sent after it still goes in at the running turn's next step. To an idle session it runs at once (it still goes as a queue, so a turn another client starts first never takes it as a steer). A worker older than queueing would steer it instead, so it is refused (to an idle session too) (`refused: this session's worker predates queueing, …; restart it`, exit 1) and nothing is sent; `chi sessions restart ID` and send again.
340
+ - It goes through the same path as the web composer (`SessionManager.deliver_turn`): the worker's Bridge when it is up, so every attached UI shows it as your message (client id `cli:send`, shown like any user message; from an agent, `agent:NAME`, labelled "agent NAME", a driver's or a visitor's: [driver and visitor](sub-agent.md#an-agents-messages-driver-and-visitor)); the input file when the worker is on its way out. During a running turn it is merged into that turn at the next step, like a message typed then, and cuts nothing. `--cut` asks for a cut, as `/cut TEXT` in a terminal does: a generation that has streamed only thinking for `steer.cut_after` seconds (per host/model: `steer_cut_after`) is cut (now, or once its thinking passes that), and the step starts again with the message. To an idle session `--cut` sends normally. `--cut --wait` into a running turn is refused like any `--wait` there (`busy: a turn is running`). `--queue` (not with `--cut`, a usage error) keeps the message for after the running turn: it runs as a turn of its own then (as `/queue TEXT` does), and a plain message sent after it still goes in at the running turn's next step. To an idle session it runs at once (it still goes as a queue, so a turn another client starts first never takes it as a steer). A worker older than queueing would steer it instead, so it is refused (to an idle session too) (`refused: this session's worker predates queueing, …; restart it`, exit 1) and nothing is sent; `chi sessions restart ID` and send again.
331
341
  - A session with no worker gets one started (like `--attach` or the web composer). A session a one-turn `chi --non-interactive` run has refuses it. Bridges listen on 127.0.0.1: another machine's sessions are reached through its chi web, `chi --remote NAME send …` ([Remote sessions](cli.md#remote-sessions)).
332
342
  - Fire and forget: it returns once the message is queued and never prints the answer; that shows in whatever is attached. A guardrail "ask" waits for a UI to answer it, so with nothing attached the turn stalls there until one attaches (`chi --attach ID`).
333
343
  - `--image PATH` (repeatable, up to 20) sends images with the message, as the web composer's chips do. Each file is read once before anything is sent (bmp, tiff and heic converted to png, large ones downscaled, as for `@path`); a missing file or one that isn't an image stops the send (exit 1; with `--wait --format json`, an `error` line) and nothing is sent; more than 20 is a usage error (exit 2). Each session gets its own copy in `<session>/images/`. Text is still required (`-m` or stdin; context alone counts), also with `--wait`. The session's model must see images: one known not to (the host's model list says text-only, `vision: false` in `models:` or `hosts:`, a native llama.cpp without a vision model) is refused before anything is sent, with the reason (`<id> refused: gemma can't take images (…); send text only or switch the model (/model)`); the other sessions of the same send still get it, and the exit is 1. With `--new` nothing is started. When chi can't tell (a native host whose `/props` doesn't answer, a list that doesn't say), the message is sent as before and a text-only model fails the turn in the session. A running turn doesn't take images mid-turn: the message runs as the next turn, and the line says `(runs after the current turn)`. With `--new` the session starts idle with the message as its preview, then the message goes in as its first turn once its worker is up (`<id> started with 1 image`); if the worker doesn't come up in 5 s the session is kept, with its id on the `failed:` line.
data/docs/sub-agent.md CHANGED
@@ -26,7 +26,9 @@ The other direction, chi sending a part of its work to a Claude Code session
26
26
  you already work with (to validate, as context, or with a question), is the
27
27
  [claude-peer bundle](bundles.md#the-claude-peer-bundle): Claude pairs with the
28
28
  chi session, chi's `claude_send` tool or `/claude` writes to Claude's inbox,
29
- and Claude's answer comes back as attached context. The
29
+ and Claude's answer comes back as attached context, its whole text in a note
30
+ of chi's conversation (Claude can also tell chi something unasked, which wakes
31
+ chi under the same count). The
30
32
  [codex-peer bundle](bundles.md#the-codex-peer-bundle) does the same with a
31
33
  Codex CLI session (`codex_send`, `/codex`, through `codex queue`). The peer's
32
34
  answers wake chi in a short loop (fix or disagree, send again) until it says
@@ -38,11 +40,54 @@ A client with no chi of its own (an iOS Shortcut, a script) can do the same
38
40
  over HTTP: one `POST …/ask` to chi web, then a wait token until the answer
39
41
  comes ([Thin clients](thin-clients.md)). An agent uses `chi send` and `chi
40
42
  answer` (with `--remote NAME` for another machine) whenever it can run chi.
41
- Over HTTP it must send `"client_id": "cli:send"` on an ask and
43
+ Over HTTP it must send `"client_id": "agent:NAME"` on an ask and
42
44
  `"client_id": "cli:answer"` on an answer: without them its lines are the
43
45
  owner's and `guardrails.parent_answers` does not hold them ([An agent over
44
46
  HTTP](thin-clients.md#an-agent-over-http)).
45
47
 
48
+ ## An agent's messages: driver and visitor
49
+
50
+ An agent's `chi send` goes in as the agent, not as you: `agent:claude`, labelled
51
+ "agent claude" in the web and the terminal. Who it is: chi's own marker first
52
+ (`SAMAGOTCHI_PARENT_SESSION`, which chi's `execute` and tasks set: `agent:chi-<id8>`,
53
+ even over `--as`, said on stderr), then `chi send --as NAME` (lowercase letters,
54
+ digits, `-` and `_`, up to 32), then `CLAUDECODE` (`claude`), `CODEX_THREAD_ID`
55
+ (`codex`), `AI_AGENT` (its value). With none of these it is yours, `cli:send`, as
56
+ before: a pipe alone is not a marker, so your own script or cron line stays yours.
57
+ The id is self-declared, as `cli:send` is: a convention for an honest agent, not a
58
+ security boundary. Every Claude Code session is `claude` unless it passes `--as`.
59
+
60
+ An agent's message can't restart a stopped session (`refused: the session is
61
+ stopped; only its owner's message starts it again`), bring back an archived one,
62
+ or run a `!` line (refused with the shell-line text). It may send session commands
63
+ (`/model x`, `/thinking low`); its `/continue yes` goes in as `chi answer`'s, held to
64
+ `guardrails.parent_answers`.
65
+
66
+ - **The driver.** The agent that created a session (`chi send --new` from Claude
67
+ Code), or the one you named (`chi send --new --driver NAME`, `/driver NAME` at a
68
+ terminal or the web), drives it: its messages are as `chi send`'s were. No extra
69
+ line, never counted; each resets the wake budget and releases the delegate
70
+ reports held back, as your message does (but never brings back an archived
71
+ session). A continue keeps the chain's driver; a fork and a delegate child have
72
+ none. Sessions an agent started before this change have no driver: name it with
73
+ `/driver claude` once.
74
+ - **A visitor.** Any other agent's message, and another chi session's
75
+ `ask_session` question, is a visitor's: its turn opens with one line naming it
76
+ (`[From the agent codex, sent with chi send; your user did not type this.]`), it
77
+ is not taken as your prompt (no objectives audit, toolkit suggestion or context
78
+ candidates for it), and it counts toward `session.max_wakes` (10 in a row), the
79
+ budget delegate, task and context wake turns use: after ten wake turns a
80
+ visitor's message is refused, and the reverse. Your next message resets the
81
+ count. A refused visitor turn ends a `--wait` with exit 1, status `refused`,
82
+ `cancel_reason: max_wakes` and the sentence `session.max_wakes turns ran in a
83
+ row with no message from this session's owner; it runs again after their next
84
+ message`; a `chi send` without `--wait` is told nothing (it printed `sent`). You
85
+ hear it once per stretch in the session's UIs. A visitor's line merged into a
86
+ running turn is not counted (the step limit bounds that turn).
87
+
88
+ Against an older worker or chi web (no `agent_sender` feature) an agent's message
89
+ goes as `chi send`'s, today's behaviour.
90
+
46
91
  ## The commands
47
92
 
48
93
  ```sh
@@ -80,7 +125,7 @@ Exit codes, both commands:
80
125
  | 3 | `question` | chi waits for an answer: `question`, `answer_with` |
81
126
  | 3 | `waiting_for_owner` | (a participant's wait, `chi --remote NAME send --wait` with their link's token) their turn waits on the session's owner: a question or an approval it raised, or the owner's step-limit Continue; wait again |
82
127
  | 4 | `running` | `--timeout` passed; the turn goes on, wait again |
83
- | 1 | `refused` | (a participant's wait) their queued turn was refused before it ran: `cancel_reason` `revoked` (their link was revoked or expired), `outdated` (their link is an older chi's read-only one) or `cap_reached` (they spent their cap); no turn ran for it |
128
+ | 1 | `refused` | the queued turn was refused before it ran, no turn ran for it: `cancel_reason` `max_wakes` (an agent's message as a visitor, past `session.max_wakes`: [driver and visitor](#an-agents-messages-driver-and-visitor)), or for a participant's wait `revoked` (their link was revoked or expired), `outdated` (their link is an older chi's read-only one) or `cap_reached` (they spent their cap) |
84
129
  | 1 | `failed`, `canceled`, `limit`, `removed`, `no_answer`, `error`, `worker_gone`, `stopped` | `detail` says what happened (`limit`: the turn ran out of steps and nobody can be asked, e.g. an older worker; `chi send ID -m '/continue yes'` continues it, except under `guardrails.parent_answers: hard`, where a parent's `/continue yes` is refused as its `chi answer --option Continue` is; `removed`: the `--queue` message waited for was taken back before it ran, no turn ran for it). `failed` adds `error_kind` (the provider error's kind: `credits`, `credits_held`, `rate_limited`, `server`, `auth`, `connection`, …) and `retryable` when known; `canceled` adds `cancel_reason` (`user`: a Stop in the web; `session_stopped`: a session stop, `chi sessions stop` or the web's; `worker_stopped`: the turn waited for (a `--queue` message's, a message's to an idle session, the running turn a message merged into or a plain `--wait` saw running) died with its worker (detail "its worker exited mid-turn"), settled by the next one; `hook`; `ctrl_c`; `manual`) and `stopped_by` (the hook that stopped it, e.g. `loop-guard`) when known |
85
130
  | 2 | (no JSON) | usage error, or an option the question doesn't offer |
86
131
  | 130 | `running` | Ctrl-C; the turn goes on |
data/docs/thin-clients.md CHANGED
@@ -44,7 +44,7 @@ another link ran it. Body fields:
44
44
  message as its own turn, and you get that turn's answer. `false` refuses a
45
45
  running session with 409 `busy`.
46
46
  - `client_id`: who is asking. Leave it out for yourself (the line is the
47
- owner's, as from the web composer). An agent sends `"cli:send"`: see
47
+ owner's, as from the web composer). An agent sends `"agent:NAME"`: see
48
48
  [An agent over HTTP](#an-agent-over-http).
49
49
  - `request_id`: your own key for this ask, 1 to 128 printable ASCII
50
50
  characters. Send the same ask again with the same `request_id` (a retry
@@ -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
@@ -127,9 +191,16 @@ the sender for it. An MCP host can add chi as an MCP server instead
127
191
  on chi web), which names it too. An agent that calls these routes itself must name itself
128
192
  the same way:
129
193
 
130
- - `"client_id": "cli:send"` on every ask (and on `POST /api/sessions`);
194
+ - `"client_id": "agent:NAME"` on every ask (and on `POST /api/sessions`), NAME
195
+ lowercase letters, digits, `-` and `_`: its turns are labelled "agent NAME" and
196
+ it is a driver or a visitor as `chi send`'s agents are ([driver and
197
+ visitor](sub-agent.md#an-agents-messages-driver-and-visitor)); `POST
198
+ /api/sessions` also takes `"driver": "agent:NAME"`;
131
199
  - `"client_id": "cli:answer"` on every answer.
132
200
 
201
+ `"cli:send"` still works and is held the same way, but it is the owner's row: it
202
+ restarts a stopped session and runs `!` lines.
203
+
133
204
  Then `guardrails.parent_answers` applies as it does to `chi send` and `chi
134
205
  answer` ([Answers from a parent agent](guardrails.md#answers-from-a-parent-agent)):
135
206
  a `/continue yes` is held to it (403 `parent_continue_refused`), a
@@ -150,14 +221,15 @@ answers the first turn.
150
221
  1. **Dictate Text** (or **Ask for Input**).
151
222
  2. **Get Contents of URL**: `https://<your chi web>/api/sessions/<id>/ask`,
152
223
  method POST, header `Authorization: Bearer <token>`, JSON body `prompt` =
153
- 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**
154
225
  `key` to **Current Date** formatted with seconds, send `request_id` = `key`,
155
226
  and if the step fails (no `status` in the answer) run it again with the same
156
227
  `key`: the retry answers the first one's turn instead of sending it twice.
157
228
  3. **Repeat** while the answer's `status` is `timeout`: **Get Contents of URL**
158
229
  for `…/api/sessions/<session_id>/wait` with the JSON body `token` = the
159
230
  answer's `token`.
160
- 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.
161
233
 
162
234
  For running chi from another agent instead (`chi send --wait`, `chi answer`),
163
235
  see [chi as a sub-agent](sub-agent.md). The routes in full are in
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "client_id"
4
+ require_relative "session_paths"
5
+
6
+ module Samagotchi
7
+ # Who an agent's message goes in as: the one seat that names the client
8
+ # id chi send, Ask#agent_line (chi web's ask, the MCP tools on this
9
+ # machine) and the MCP tools to another machine send a message with. An
10
+ # agent is named by --as, else by the marker its process carries
11
+ # (Guardrails::ParentApprovals::AGENT_MARKERS); none is the owner (a pipe
12
+ # alone is not a marker: the owner's own script stays the owner's). The id
13
+ # is self-declared, as chi send's is: a convention for an honest agent,
14
+ # not a security boundary. No Engine, so a command loads it cheaply.
15
+ module AgentCaller
16
+ # A name: lowercase letters, digits, - and _ (ClientId::AGENT_NAME_MAX).
17
+ NAME = /\A[a-z0-9_-]{1,#{ClientId::AGENT_NAME_MAX}}\z/
18
+ # The name a marker gives when its value is not one.
19
+ FALLBACK = "agent"
20
+ # chi's own marker (execute and tasks set it, the model can't change it):
21
+ # its session's first 8 characters, or "chi" for a run with no session.
22
+ # Guardrails::ParentApprovals::PARENT_SESSION_ENV's (a spec keeps them
23
+ # the same: that file is too big a load for chi send's start).
24
+ PARENT_SESSION = "SAMAGOTCHI_PARENT_SESSION"
25
+ # The vendors' markers, in order, and the name each gives (nil: its
26
+ # value, cleaned).
27
+ VENDOR_MARKERS = [%w[CLAUDECODE claude], %w[CODEX_THREAD_ID codex], ["AI_AGENT", nil]].freeze
28
+
29
+ module_function
30
+
31
+ # +name+ as an agent's name (lowercased), or nil when it isn't one: the
32
+ # name reaches a header the model reads, so it is never free text.
33
+ def clean(name)
34
+ text = name.to_s.strip.downcase
35
+ text.match?(NAME) ? text : nil
36
+ end
37
+
38
+ # The caller's name, or nil for the owner: chi's own marker first, even
39
+ # over +as+ (a worker inherits its spawner's environment, so a chi
40
+ # session's own model may carry CLAUDECODE too); then +as+; then the
41
+ # vendors' markers.
42
+ # @param as [String, nil] chi send --as's (cleaned before: #clean)
43
+ def name(env: ENV, as: nil)
44
+ parent = env.fetch(PARENT_SESSION, "").to_s.strip
45
+ return parent_name(parent) unless parent.empty?
46
+ return as unless as.to_s.empty?
47
+
48
+ VENDOR_MARKERS.each do |key, given|
49
+ value = env.fetch(key, "").to_s.strip
50
+ next if value.empty?
51
+
52
+ return given || clean(value) || FALLBACK
53
+ end
54
+ nil
55
+ end
56
+
57
+ # Whether chi's own marker names this process (chi send --as is ignored
58
+ # there).
59
+ def inside_chi?(env: ENV) = !env.fetch(PARENT_SESSION, "").to_s.strip.empty?
60
+
61
+ # chi send's sender from its --as (+as+, as typed) and +env+: the name
62
+ # (nil: the owner), a usage error for an --as that is no name, and a note
63
+ # for stderr when --as is ignored (inside a chi session).
64
+ # @return [Array(String, String, String)] name, error, note (each may be nil)
65
+ def send_name(as:, env: ENV)
66
+ return [name(env: env), nil, nil] if as.nil?
67
+
68
+ clean = clean(as)
69
+ return [nil, "--as takes a name: lowercase letters, digits, - and _, up to #{ClientId::AGENT_NAME_MAX}, not #{as}", nil] unless clean
70
+
71
+ note = "--as ignored: this runs inside a chi session, which names the sender" if inside_chi?(env: env)
72
+ [name(env: env, as: clean), nil, note]
73
+ end
74
+
75
+ # The client id a message from this caller goes in as: an agent's
76
+ # (agent:<name>), or chi send's, the owner's, with no name.
77
+ # @param name [String, nil] the agent's name (#name)
78
+ # @return [String]
79
+ def send_id(name: nil)
80
+ name.to_s.empty? ? ClientId::CLI_SEND : ClientId.agent(name)
81
+ end
82
+
83
+ # A /continue yes from +id+ (a parent line, ClientId.parent_line?) goes
84
+ # in as chi answer's, held to guardrails.parent_answers; any other id as
85
+ # given.
86
+ def continue_id(id) = ClientId.parent_line?(id) ? ClientId::CLI_ANSWER : id
87
+
88
+ # "chi" (Tools::Builtins.parent_env's, a run with no session) or
89
+ # anything not an id: "chi".
90
+ def parent_name(value)
91
+ return "chi" if value == "chi" || !SessionPaths.valid_id?(value)
92
+
93
+ clean("chi-#{value[0, 8]}") || "chi"
94
+ end
95
+ private_class_method :parent_name
96
+ end
97
+ end
@@ -809,7 +809,8 @@ module Samagotchi
809
809
  SessionInbox::UNQUEUE_FEATURE, Delivery::REVIEW_FEATURE, Delivery::PAIR_FEATURE, TurnDrawings::FEATURE,
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
- WorkingSet::ITEM_FEATURE, BlockFix::FEATURE].freeze
812
+ WorkingSet::ITEM_FEATURE, BlockFix::FEATURE, Delivery::AGENT_FEATURE,
813
+ Delivery::ASK_FEATURE, ReplyFor::FEATURE].freeze
813
814
 
814
815
  # The routes, by method and what follows /session/:id/: a handler takes
815
816
  # the session id and the request body and returns [headers, status, body].
@@ -1095,9 +1096,8 @@ module Samagotchi
1095
1096
  client_id = fetched(parsed, "client_id")
1096
1097
  return UNNAMED_COMMAND_REPLY if client_id.to_s.strip.empty?
1097
1098
 
1098
- # Only the owner's senders and chi answer's (CommandIntake.allowed?),
1099
- # as for a command sent as a message.
1100
- unless CommandIntake.allowed?(client_id)
1099
+ # As for a command sent as a message (CommandIntake: refused? first, then allowed?).
1100
+ if CommandIntake.refused?(line, client_id) || !CommandIntake.allowed?(client_id)
1101
1101
  Log.warn(:bridge, "command_refused", client_id: client_id)
1102
1102
  return [{}, 403, { error: CommandIntake::REFUSED_ERROR, detail: CommandIntake.refusal(line) }]
1103
1103
  end
@@ -1342,11 +1342,11 @@ module Samagotchi
1342
1342
  # schedule's or a plugin's /word line is a prompt, its shell line
1343
1343
  # refused (403, nothing queued).
1344
1344
  if images.empty? && @on_command && command_registry.command?(prompt.to_s)
1345
- if CommandIntake.allowed?(client_id)
1346
- return queue_command_request(sid, prompt.to_s.strip, client_id: client_id, deadline: deadline, author: author)
1347
- elsif CommandIntake.shell_line?(prompt)
1345
+ if CommandIntake.refused?(prompt, client_id) # an agent's ! line too: before allowed? would queue it
1348
1346
  Log.warn(:bridge, "shell_line_refused", client_id: client_id)
1349
1347
  return [{}, 403, { error: CommandIntake::REFUSED_ERROR, detail: CommandIntake::REFUSED }]
1348
+ elsif CommandIntake.allowed?(client_id)
1349
+ return queue_command_request(sid, prompt.to_s.strip, client_id: client_id, deadline: deadline, author: author)
1350
1350
  end
1351
1351
  end
1352
1352
  return CommandIntake::PRIVATE_REFUSED if command_registry.private_args?(prompt.to_s) # never a message