samagotchi 0.91.0 → 0.92.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 (70) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -1
  3. data/README.md +5 -2
  4. data/bin/chi +4 -4
  5. data/docs/architecture.md +16 -12
  6. data/docs/bundle-authoring.md +2 -1
  7. data/docs/cli.md +5 -5
  8. data/docs/configuration.md +3 -1
  9. data/docs/context.md +5 -3
  10. data/docs/hooks.md +3 -3
  11. data/docs/internals/background-tasks.md +2 -2
  12. data/docs/internals/bundles.md +4 -4
  13. data/docs/internals/engine.md +21 -8
  14. data/docs/internals/tool-guardrails.md +10 -2
  15. data/docs/memory.md +6 -0
  16. data/docs/plugins.md +30 -13
  17. data/docs/releasing.md +3 -0
  18. data/docs/sessions.md +3 -3
  19. data/lib/samagotchi/bridge.rb +8 -9
  20. data/lib/samagotchi/bundle_command/check.rb +43 -12
  21. data/lib/samagotchi/bundle_command/scaffold.rb +12 -0
  22. data/lib/samagotchi/bundle_command/test_run.rb +12 -0
  23. data/lib/samagotchi/bundle_command/try/command.rb +164 -0
  24. data/lib/samagotchi/bundle_command/try/render.rb +80 -0
  25. data/lib/samagotchi/bundle_command/try/run.rb +35 -17
  26. data/lib/samagotchi/bundle_command/try/sandbox.rb +113 -34
  27. data/lib/samagotchi/bundle_command/try/trace.rb +20 -26
  28. data/lib/samagotchi/bundle_command.rb +11 -213
  29. data/lib/samagotchi/bundle_session_settings.rb +82 -45
  30. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/cost-cap/manifest.yml +6 -5
  32. data/lib/samagotchi/bundles/cost-cap/plugin.rb +57 -12
  33. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  34. data/lib/samagotchi/child_env.rb +50 -0
  35. data/lib/samagotchi/engine.rb +22 -12
  36. data/lib/samagotchi/hooks/registry.rb +2 -0
  37. data/lib/samagotchi/kernel_loop.rb +14 -3
  38. data/lib/samagotchi/llm/chat_loop.rb +3 -1
  39. data/lib/samagotchi/llm/errors.rb +4 -4
  40. data/lib/samagotchi/memory_bundle/builder.rb +3 -2
  41. data/lib/samagotchi/memory_bundle/installed_bundle.rb +7 -2
  42. data/lib/samagotchi/memory_bundle/installer.rb +1 -0
  43. data/lib/samagotchi/memory_bundle/manifest.rb +42 -8
  44. data/lib/samagotchi/memory_bundle/provenance.rb +2 -1
  45. data/lib/samagotchi/parent_report.rb +12 -0
  46. data/lib/samagotchi/reply_wait.rb +6 -2
  47. data/lib/samagotchi/sandbox_layout.rb +66 -0
  48. data/lib/samagotchi/send_command.rb +3 -3
  49. data/lib/samagotchi/session_manager.rb +12 -20
  50. data/lib/samagotchi/task_watch.rb +64 -21
  51. data/lib/samagotchi/testing/bundle.rb +32 -19
  52. data/lib/samagotchi/testing/install.rb +26 -17
  53. data/lib/samagotchi/testing/sandbox.rb +45 -37
  54. data/lib/samagotchi/testing/waiting.rb +5 -7
  55. data/lib/samagotchi/tool_response.rb +28 -6
  56. data/lib/samagotchi/tools/task_runtime.rb +2 -2
  57. data/lib/samagotchi/turn_checkpoint.rb +23 -10
  58. data/lib/samagotchi/version.rb +1 -1
  59. data/lib/samagotchi/web/public/app.js +24 -14
  60. data/lib/samagotchi/web/public/cards_place.js +4 -1
  61. data/lib/samagotchi/web/public/images.js +6 -0
  62. data/lib/samagotchi/web/public/model_pick.js +10 -0
  63. data/lib/samagotchi/web/public/toasts.js +17 -9
  64. data/lib/samagotchi/web/public/unqueue.js +20 -4
  65. data/lib/samagotchi/worker.rb +77 -185
  66. data/lib/samagotchi/worker_idle_exit.rb +20 -5
  67. data/lib/samagotchi/worker_inbound.rb +5 -5
  68. data/lib/samagotchi/worker_task_wakes.rb +160 -0
  69. data/lib/samagotchi/worker_wakes.rb +0 -3
  70. metadata +6 -1
data/docs/plugins.md CHANGED
@@ -31,7 +31,8 @@ plugin:
31
31
  requires_chi: ">= 0.1.28" # optional: a gem-style requirement (">= 0.1.28, < 0.2"); the bundle's hooks/ check it too
32
32
  # requires_chi_next: true # shipped bundles only, ignored by chi: rake release:bump raises requires_chi
33
33
  # to the chi being released (docs/releasing.md)
34
- session_settings: [cap] # optional: the settings a session may set (chi --set my-bundle.cap=3)
34
+ session_settings: [cap] # optional: the settings a session may set (chi --set my-bundle.cap=3);
35
+ # {cap: number} types them: number (or off), boolean, string or any
35
36
  needs: [gh] # optional: outside commands it relies on (see memory.md#bundles-that-need-outside-commands)
36
37
  ```
37
38
 
@@ -766,10 +767,13 @@ A bundle's settings are config.yml's, for every session. A setting a session may
766
767
  say) is one the manifest lists in `session_settings:`; `chi --set BUNDLE.KEY=VALUE` and `chi send --new --set …`
767
768
  then give it to a new session, saved with it (a respawn, a fork and a continued link keep it; a delegate child
768
769
  doesn't). chi refuses a bundle that isn't installed (or whose plugin doesn't load) and a key the manifest doesn't
769
- list, so a typo isn't saved. Values are typed simply: an integer (`3`, `-1`) or a decimal (`2.5`) is a number,
770
- `true` is true, `false` and `off` are false, and anything else stays the text as given (`010`, `0x10`, `3:30`,
771
- `No`, `null`); `POST /api/sessions` `bundle_settings` types its strings the same way and keeps JSON numbers and
772
- booleans. `ctx.settings` is the config's section with the session's values laid over it (one level: a session's
770
+ list, so a typo isn't saved. A manifest that types a key (`session_settings: {cap: number}`: `number`, which
771
+ takes off too, `boolean`, `string`, or `any`) gets only a value of that type: `--set my-bundle.cap=five` is refused,
772
+ exit 2, as a key it doesn't list is (a mapping needs a chi newer than 0.91.0). Values are typed simply: an integer (`3`, `-1`) or a decimal (`2.5`, `.5`, `1e1`)
773
+ is a number, `true`, `yes` and `on` are true, `false`, `no` and `off` are false (any case, as config.yml's YAML reads
774
+ them), and anything else stays the text as given (`010`, `0x10`, `3:30`, `y`, `null`; YAML would read the first
775
+ three as numbers and `null` as nothing); a key typed `string` keeps its text as given (`yes`, `5`, `1.10`); `POST /api/sessions` `bundle_settings` types its strings the same way and
776
+ keeps JSON numbers and booleans. `ctx.settings` is the config's section with the session's values laid over it (one level: a session's
773
777
  `cap` replaces the config's `cap`). Read such a key from `ctx.settings` where it is used, not in
774
778
  `initialize(settings)`: that runs once at load, before any session, and gets the config only.
775
779
 
@@ -1195,7 +1199,8 @@ bundle.shutdown
1195
1199
  parts (`reported:`, `estimated:`, `side:`, `known:`; `total` is reported + estimated) or a callable giving either,
1196
1200
  called at each read (a counting lambda shows whether the bundle read it).
1197
1201
  - **`session_settings:`** (on `Bundle.load` and `bundle.set`) are the session's own `--set` values for the bundle,
1198
- keys its manifest lists in `session_settings:` (another raises `ArgumentError`, as chi refuses it). `ctx.settings`
1202
+ keys its manifest lists in `session_settings:` (another key, or a value of another type than the manifest gives
1203
+ it, raises `ArgumentError`, as chi refuses it). `ctx.settings`
1199
1204
  lays them over `settings:` through chi's own `Context#settings`; the plugin's `initialize(settings)` gets
1200
1205
  `settings:` only. `bundle.set(session_settings:)` moves the session to a new id (`test-session-2`, or the
1201
1206
  `session_id:` given beside it): chi never changes them within a session, and builds `ctx.settings` once per id.
@@ -1218,7 +1223,8 @@ docs/testing.md). **Minitest:** `require "samagotchi/testing/minitest"` and subc
1218
1223
  - **From the command line:** `chi bundle test [PATH]` runs a bundle's `test/**/*_test.rb` (or `spec/`) on the
1219
1224
  Ruby and lib chi runs on, and `chi bundle check [PATH] [--fix]` runs `Install` (and the manifest, sha and
1220
1225
  `requires_chi` checks) in a sandbox ([cli.md](cli.md#writing-a-bundle-new-test-check)). `chi bundle new NAME`
1221
- writes a test to start from.
1226
+ writes a test to start from. `chi bundle try PATH -p TEXT` runs it against a real model for one turn
1227
+ ([cli.md](cli.md#trying-a-bundle)), and `chi bundle install --dev PATH` links it into your own sessions.
1222
1228
 
1223
1229
  ## The btw bundle
1224
1230
 
@@ -1615,7 +1621,10 @@ bundles:
1615
1621
  a command, not an answer: a parent that sends it (`chi send ID -m '/cap 10'`) raises the cap under any strategy.
1616
1622
  - **The cap of a session:** the one `/cap` or a Continue set for it, else its own `cap:` (`chi --set
1617
1623
  cost-cap.cap=3`, `chi send --new --set cost-cap.cap=3`; `--set cost-cap.cap=off`, `0` or a negative number for none), else `child:` for a
1618
- delegate child, else `default:`. Delegates and continued links each have their own cap (a continued link keeps
1624
+ delegate child, else `default:`. A cap is a number (`3`, `.5`, `1e1`; in config.yml and `/cap`, `"$2"` too, which `--set` refuses). `--set` refuses
1625
+ another value (`cost-cap.cap=five`: exit 2); one in config.yml (or set before this check) that doesn't read
1626
+ (`default: five`) gets one notice, `cost-cap: default: "five" isn't a number or off; no cap`, and a `cap:` or
1627
+ `child:` that doesn't read gives way to the next key (`…; using default: ($5.00)`), never a silent no cap. Delegates and continued links each have their own cap (a continued link keeps
1619
1628
  the `--set` cap, not a `/cap` or Continue); there is no family cap.
1620
1629
  - **A host it can't watch:** a model that reports no cost and has no configured price (a local server, a free
1621
1630
  model that reports 0) reads unknown: one notice, `the $3.00 cap can't be enforced: <model> reports no cost and has
@@ -1626,7 +1635,7 @@ bundles:
1626
1635
 
1627
1636
  - `/cap`: `cost-cap: $1.20 spent of $3.00 (reported $1.10, estimated $0.10, side $0.02)`, or `cost-cap: no cap
1628
1637
  ($1.20 spent)`, with `(can't be enforced: no cost reported or priced)` when it can't be.
1629
- - `/cap 5` or `/cap $5`: the cap (and what Continue adds) becomes $5.00 for this session. A cap at or under the
1638
+ - `/cap 5`, `/cap $5` or `/cap .5`: the cap (and what Continue adds) becomes $5.00 for this session. A cap at or under the
1630
1639
  spend is allowed: the next generation asks.
1631
1640
  - `/cap off` (or `/cap 0`): no cap for this session, over the config's `default:`.
1632
1641
 
@@ -2254,7 +2263,7 @@ crash, TERM), chi shuts the session's Engine down:
2254
2263
  Plugins load when a session starts (`Engine.new`, in the REPL or a
2255
2264
  worker), after the bundle hooks. The steps are:
2256
2265
 
2257
- 1. The file must match the sha256 recorded at install.
2266
+ 1. The file must match the sha256 recorded at install (not checked for a bundle installed with `--dev`).
2258
2267
  2. chi must meet `requires_chi`.
2259
2268
  3. The file is `module_eval`'d into a new module in the bundle's namespace
2260
2269
  (`Samagotchi::Bundles::<bundle>`).
@@ -2280,9 +2289,11 @@ a bundle's hooks. **Installing a bundle means trusting it**, as you would a
2280
2289
  gem.
2281
2290
 
2282
2291
  - The sha256 is an integrity check, not proof of who wrote the file. A file
2283
- edited after install is not loaded until you reinstall the bundle.
2284
- - Install only copies the file. The code first runs at the next session
2285
- start.
2292
+ edited after install is not loaded until you reinstall the bundle. A
2293
+ `--dev` install skips that check for its own bundle: its files are the
2294
+ source directory's, and an edit loads at the next start.
2295
+ - Install only copies the file (`--dev` links it). The code first runs at the
2296
+ next session start.
2286
2297
  - Guardrail rules keyed by a tool's name apply to plugin tools, as they do to
2287
2298
  chi's own tools; path and command rules see what `targets:` says.
2288
2299
 
@@ -2301,6 +2312,12 @@ gem.
2301
2312
  `requires_chi`, its `scripts/` and `context_providers:`) into the built
2302
2313
  bundle.
2303
2314
  - `chi bundle uninstall <name>`: removes the plugin with the bundle.
2315
+ - `chi bundle install --dev <dir>`: links the bundle's plugin, hooks, rules and scripts to `<dir>` instead of
2316
+ copying them, with no sha256 check, so an edit applies at the next worker start
2317
+ ([cli.md](cli.md#writing-a-bundle-new-test-check)).
2318
+ - `chi bundle new`, `test` and `check`: start a bundle, run its tests on chi's Ruby, check it as an install takes
2319
+ it ([cli.md](cli.md#writing-a-bundle-new-test-check)); `chi bundle try PATH -p TEXT`: run it for one turn in a
2320
+ sandbox and trace what it did ([cli.md](cli.md#trying-a-bundle)). The path: [bundle-authoring.md](bundle-authoring.md).
2304
2321
 
2305
2322
  ## Not yet
2306
2323
 
data/docs/releasing.md CHANGED
@@ -61,6 +61,9 @@ as the GitHub release body.
61
61
  | `rake bundles:sha` | Recomputes the sha256 lines of every shipped bundle manifest (`files:`, `hooks:`, `plugin:`). |
62
62
  | `rake bundles:check` | Sha lines match; every top-level `*.md` of a bundle is listed in its `files:` (an install takes only the listed ones); a bundle changed since the last `v*` tag has a higher version (skipped, with a note, before the first tag). Warns (doesn't fail) when such a bundle's `requires_chi` still admits the tagged chi: mark it `requires_chi_next` if the change uses anything new. Notes a bundle marked `requires_chi_next`, and a profile (`core`, `dev`) whose `requires_chi` is below a member's. The release workflow and `release:check` run it in full. |
63
63
  | `rake 'bundles:check[ci]'` | The CI workflow's (every push and PR): the same, except the version check leaves out the system bundle, which is changed and unbumped between releases (`release:bump` moves its version with VERSION). A task argument, not `CI=1`: GitHub sets `CI` in the release workflow too. |
64
+ | `rake bundles:specs` | The shipped bundles' own specs (`lib/samagotchi/bundles/*/spec`) on the bundle test kit alone (no `spec_helper`), as an external bundle's run. CI runs it as its own step. |
65
+ | `rake lint` / `rake lint:fix` | RuboCop over the repo (must report no offenses; CI runs it) / its safe autocorrect (`rubocop -a`). |
66
+ | `rake gem:validate`, `gem:build`, `gem:install`, `gem:clean` | Check the gemspec; build the gem into `pkg/`; build and install it locally; remove the built gems. |
64
67
  | `rake release:draft_changelog` | A draft Unreleased section from the commit subjects since the last tag, grouped. Stdout only. |
65
68
  | `rake release:bump[X.Y.Z]` | VERSION, the system manifest, Gemfile.lock, CHANGELOG, and `requires_chi: ">= X.Y.Z"` for each bundle marked `requires_chi_next` (the marker dropped). No commit. |
66
69
  | `rake release:check` | Clean tracked tree, VERSION == system bundle, a CHANGELOG section, no `requires_chi_next` left, `bundles:check`, `rake lint` (RuboCop), rspec (both roots: `spec` and the bundles' own `spec/`) + `rake bundles:specs` + npm test, `gem build`, then a clean install into a temp GEM_HOME that runs `chi --version`, `chi self` and `chi bundle list` with a temp HOME. Needs the network (gem dependencies). |
data/docs/sessions.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Sessions are plain files — no DB. Each session is `~/.local/state/samagotchi/sessions/<uuid>.json` (XDG-aware via `XDG_STATE_HOME`) plus a sidecar dir `<uuid>/` with `input/`/`notes/`/`output/`/`owner.lock`/`bridge.json` (`Session.session_dir`), and `tool_output/` once a long `execute` result was cut: its whole output, which the cut result names (`ToolOutputFiles`, the newest 50 kept; see [Tool output guardrails](internals/tool-guardrails.md#the-runners-cut-max_tool_output_chars)). Besides the messages and turn state, the JSON keeps `used_memory_names` (what the session read), `preloaded_memory_names` (`--memory`) and `muted_memory_names` (`--mute`), the last two written before the worker starts so a respawn builds the same prompt, `prompt_notes`, the model notes the system prompt carried at its last build (`[{name, scope, chars, digest}]`, see [Memory](memory.md#model-notes)), `parent_id`, the session that delegated this one (see *Delegating*; `null` otherwise), and `continues`, the session this one continues (the previous link of a chain, see *Session chains*; `null` otherwise); files from before those keys read as empty lists, no parent and no previous link. `model_name` is the resolved model ref (an alias applied, `host:id` when it names a host), so a resumed session keeps its model when an alias is retargeted; `model_typed` is the name it was given as when that differs (an alias), for the `models:` lookup after a resume (`null` otherwise).
4
4
 
5
- **Input files:** a message for a session's worker waits in `input/<timestamp>.json` (`SessionInbox.write_input`: `prompt`, `client_id`, `enqueued_id`, and `images`, `no_interrupt` and `delivery` when they apply; `delivery` is written only for `"queue"`). While a turn runs, the worker merges them at each step boundary in name order, except a queued one or one with images: those wait for the turn's end and run one turn each, in name order, and a file after them still merges (`Worker#pending_input_drain`). A queue is sent only to a worker whose `bridge.json` names the `delivery` feature; an older one would steer it, so `SessionManager.deliver_turn` refuses it (409 `delivery_unavailable`), and any other 4xx the Bridge answers is a refusal too, never a fallback file (except a 413, a body over its size limit: that one still goes in as a file, its `delivery` kept). A session command recognized in a file runs without a turn; its completed outcome is kept at `input/settled/<enqueued_id>` so `chi send --wait` ends instead of waiting for a turn that will not run. **Reply files:** a turn that ends with visible text leaves its reply in `output/<timestamp>.txt`, or `output/<timestamp>-<enqueued_id>.txt` when the turn ran an input file with an id (`SessionInbox.write_output`), and the session's `last_turn` keeps that `enqueued_id`; so a wait for one queued message (`chi send --queue --wait`, `ReplyWait`'s `turn:`) finds its own turn's reply or end, never another turn's. The names still sort by time, and every reader takes `*.txt`.
5
+ **Input files:** a message for a session's worker waits in `input/<timestamp>.json` (`SessionInbox.write_input`: `prompt`, `client_id`, `enqueued_id`, and `images`, `no_interrupt` and `delivery` when they apply; `delivery` is written only for `"queue"`). While a turn runs, the worker merges them at each step boundary in name order, except a queued one or one with images: those wait for the turn's end and run one turn each, in name order, and a file after them still merges (`Worker#pending_input_drain`). A queue is sent only to a worker whose `bridge.json` names the `delivery` feature; an older one would steer it, so `SessionManager.deliver_turn` refuses it (409 `delivery_unavailable`), and any other 4xx the Bridge answers is a refusal too, never a fallback file (except a 413, a body over its size limit: that one still goes in as a file, its `delivery` kept). A session command recognized in a file runs without a turn; its outcome is kept at `input/settled/<enqueued_id>` (`completed`, `failed` for a command error, `canceled` with `cancel_reason` `busy` or `dropped` for one refused mid-turn or dropped as the worker left; `origin: command`) so `chi send --wait` ends instead of waiting for a turn that will not run, its detail saying `the command failed` or `the command was refused (busy)` rather than a turn's words. **Reply files:** a turn that ends with visible text leaves its reply in `output/<timestamp>.txt`, or `output/<timestamp>-<enqueued_id>.txt` when the turn ran an input file with an id (`SessionInbox.write_output`), and the session's `last_turn` keeps that `enqueued_id`; so a wait for one queued message (`chi send --queue --wait`, `ReplyWait`'s `turn:`) finds its own turn's reply or end, never another turn's. The names still sort by time, and every reader takes `*.txt`.
6
6
 
7
7
  **Removing a queued message:** a message queued for after the running turn (`chi send --queue`, the web's Alt+Enter, `/queue TEXT` in a terminal), or one with images (it waits for the turn's end too), can be taken back while it still waits: the worker's Bridge (`POST /session/:id/turn/dequeue {enqueued_id}`, the `unqueue` feature) deletes its input file and every UI drops it (`:turn_dequeued`). It is a race with the turn's end, decided by the same rename the worker uses to take the file: once a turn took it the answer is `409 already_started` (it runs), and an id the worker no longer knows is `404 unknown_enqueued_id`. A plain message sent without `--queue` is not removable (`409 not_queued`): a running turn's next step may take it at any moment. A wait for its turn (`chi send --queue --wait`, a delegate follow-up's wait) ends at once with `removed` (the tombstone `input/removed/<enqueued_id>` says so), and a `chi -p` run whose queued prompt went ends with exit 1. The `200` carries the removed `prompt`: the web and the attached terminal put it back into the composer to edit (not its images). The images a removed message named stay in the session's `images/`. Not removable: a queued session command (`/queue /model x`: it waits in the worker, not in `input/`), a message in a stopped worker's inbox (the next worker runs it), and the plain REPL's (`--no-shared`) own queue.
8
8
 
@@ -17,7 +17,7 @@ Sessions are plain files — no DB. Each session is `~/.local/state/samagotchi/s
17
17
 
18
18
  A session is deleted if **expired by age OR overflow by count** (unless `keep_status` or the live-owner guard: a session a worker or `chi` still has open is never pruned). A session's `status` is its turn state (`idle`/`running`), not whether a worker is alive. Orphan dirs without a `*.json` are never deleted, except skeleton-only ones (see *Empty sessions*). Deletion removes both `*.json` and sidecar dir atomically. Set both `DAYS=0` and `MAX=0` to retain forever.
19
19
 
20
- **Worker idle exit:** a background worker (plain `chi`, Web UI sessions) exits after `SAMAGOTCHI_SESSION_IDLE_EXIT_MINUTES` (`session.idle_exit_minutes`, default `30`, `0`=never) with no turn running or queued, no client on its stream (an open web tab or attached terminal keeps it), no reminder registered, no background task it watches for a [finish wake](internals/background-tasks.md#finish-wake) still running (with `session.task_wakes: wake`) and no continue offer (the step-limit question) waiting for an answer. It removes `bridge.json` and frees `owner.lock`; the next prompt or `--attach` wakes a new worker (`WorkerIdleExit`, `SessionManager.run_session_loop`). A client can also ask the worker to exit right away (Bridge `POST /session/:id/exit`; `/exit` in an attached terminal does, `/detach` doesn't): the same rules apply without the timeout (even with `0`), and the asker's own stream doesn't count. The reply names what keeps it up (for background tasks, which ones and how to stop them). The session's status stays as it was, not `stopped`. With `"restart": true` (a worker whose sidecar lists the `restart` feature) the worker hands the session to a new worker on the newest chi installed: it leaves, then starts its successor once its lock is free, keeping even an empty session and writing no recap. Clients' streams don't hold a restart (a web tab and an attached terminal reconnect to the new worker); what would be lost does: a turn running or queued, a continue offer, a question or approval waiting, reminders, a `/btw` (or another anytime command) still running, a delegate's approval relay open or settled in the last 10 minutes, and background tasks this conversation started that still run (`WorkerIdleExit#hold_for_restart`; 409 `held` with `reason`). What lives only in the worker's memory goes: the event history a late client replays, the kept `/btw` answers, a plugin's in-memory state.
20
+ **Worker idle exit:** a background worker (plain `chi`, Web UI sessions) exits after `SAMAGOTCHI_SESSION_IDLE_EXIT_MINUTES` (`session.idle_exit_minutes`, default `30`, `0`=never) with no turn running or queued, no client on its stream (an open web tab or attached terminal keeps it), no reminder registered, no background task it watches for a [finish wake](internals/background-tasks.md#finish-wake) still running or waiting for its wake turn (with `session.task_wakes: wake`; not one whose turn you stopped) and no continue offer (the step-limit question) waiting for an answer. It removes `bridge.json` and frees `owner.lock`; the next prompt or `--attach` wakes a new worker (`WorkerIdleExit`, `SessionManager.run_session_loop`). A client can also ask the worker to exit right away (Bridge `POST /session/:id/exit`; `/exit` in an attached terminal does, `/detach` doesn't): the same rules apply without the timeout (even with `0`), and the asker's own stream doesn't count. The reply names what keeps it up (for background tasks, which ones and how to stop them). The session's status stays as it was, not `stopped`. With `"restart": true` (a worker whose sidecar lists the `restart` feature) the worker hands the session to a new worker on the newest chi installed: it leaves, then starts its successor once its lock is free, keeping even an empty session and writing no recap. Clients' streams don't hold a restart (a web tab and an attached terminal reconnect to the new worker); what would be lost does: a turn running or queued, a continue offer, a question or approval waiting, reminders, a `/btw` (or another anytime command) still running, a delegate's approval relay open or settled in the last 10 minutes, and background tasks this conversation started that still run (`WorkerIdleExit#hold_for_restart`; 409 `held` with `reason`). What lives only in the worker's memory goes: the event history a late client replays, the kept `/btw` answers, a plugin's in-memory state.
21
21
 
22
22
  **Empty sessions:** a session nothing happened in is deleted when it is left, so `chi` → `/exit` leaves no trace. Empty means: no messages, no turn tried (a failed turn leaves a `last_prompt` and keeps it), no memory used, no pending question, nothing in `input/`, `notes/` or `images/`, nothing in its dir beyond the worker's skeleton, mode `assist`, and the default model. A session on another model (`/model`, `--model`) counts as prepared and stays (`SessionManager.discardable?`). The worker checks as it idle-exits or leaves on a client's request and deletes it once its lock is free, checking again first. The attached `/exit` then says `Detached; the session is empty: it will be discarded if nothing arrives before its worker stops.` (a note or prompt landing first keeps it). The REPL (`--no-shared`) does the same at `/exit` or Ctrl-D. The retention sweep catches those killed first: empty sessions over an hour old with no live owner, whatever `DAYS`/`MAX`, and skeleton-only dirs with no `*.json`. `session.keep_empty: true` (env `SAMAGOTCHI_SESSION_KEEP_EMPTY`) turns all of it off.
23
23
 
@@ -211,7 +211,7 @@ chi send --new --continues last:3fa2 -m "new day" # the next link of 3fa2's
211
211
  - Exit codes with `--wait`: 0 answered; 3 the turn waits for an answer from you (a question, a hook's question, a guardrail approval, or the step-limit question: see [chi as a sub-agent](sub-agent.md#the-step-limit)), and the session keeps waiting: stderr gets the whole question (`waiting for an answer (approval): …`, its text, the numbered options, whether free text is allowed) and how to answer it (`chi answer ID --question QID --option N`, or `chi --attach ID`, the web); 4 `--timeout S` passed with the turn still running (it goes on; wait again); 1 the turn ended without a reply (canceled, failed or empty), the worker failed or vanished, or the session was stopped; 130 on Ctrl-C, which leaves the turn running (`still running: chi --attach ID`). There is no default timeout.
212
212
  - `--format json` (with `--wait`) prints one JSON object on stdout however the wait ends, for a script or a parent agent (see [chi as a sub-agent](sub-agent.md)): `{"status":"answered","session_id":…,"text":…}`; `{"status":"question",…,"question":{"id","kind","header","text","options","multi_select","allow_freeform","approval"},"answer_with":"chi answer ID --question QID --option N"}`, where `kind` is `question` (the model's), `hook` or `approval` (with the tool, command, cwd, rule, reason and offered scopes); `{"status":"running",…,"detail":…}` (exit 4, and on Ctrl-C); and `failed`, `canceled`, `removed` (a `--queue --wait` message taken back before it ran), `no_answer`, `error`, `worker_gone` or `stopped` with a `detail` line (exit 1); `failed` adds `error_kind` and `retryable`, `canceled` adds `cancel_reason` (`worker_stopped`: the turn waited for died with its worker and the next worker settled it) and `stopped_by`, when known. A failure before the wait (no such session, a busy one) is `error` too. A usage error (exit 2) prints no JSON.
213
213
  - `--wait ID` with no message (no `-m`, nothing piped) sends nothing: it waits for the session's next reply and prints and exits as above. With a turn running, that turn's reply (its `interrupted_turn` mark names it), not a turn's queued behind it; with the step-limit question standing, the reply of the turn its Continue runs; with an idle session whose last turn already ended, that ended turn is the answer: its reply, or its end when it left no reply — a turn that finished in the gap between waits is reported, not waited for. With none of those (or a worker whose `bridge.json` lacks `turn_ids`), the next reply of any turn. A running session is fine (that is the point), so after exit 3, 4 or 130 an agent waits again this way while the user answers in the web or `chi --attach`; the question pending when it starts doesn't count again. An idle session with no worker waits until something wakes one. With `--new`, or two ids, it is a usage error (exit 2).
214
- - `--set BUNDLE.KEY=VALUE` (with `--new`, repeatable) gives the new session a bundle setting of its own, as `chi --set` does (see *Bundle settings* below): `chi send --new --set cost-cap.cap=3 -m "…"` starts it with a $3 cap. A bundle or key the installed bundles don't offer is a usage error (exit 2), as is `--set` without `--new`.
214
+ - `--set BUNDLE.KEY=VALUE` (with `--new`, repeatable) gives the new session a bundle setting of its own, as `chi --set` does (see *Bundle settings* below): `chi send --new --set cost-cap.cap=3 -m "…"` starts it with a $3 cap. A bundle or key the installed bundles don't offer, or a value of another type than the manifest gives the key (`cost-cap.cap=five`), is a usage error (exit 2), as is `--set` without `--new`.
215
215
  - `--parent-answers LEVEL` (with `--new`) gives the new session its own `guardrails.parent_answers` (`hard`, `standard`, `soft`), tighten-only: config.yml's applies when it is stricter, with `chi send: warning: --parent-answers soft is looser than config.yml's …`. See *Parent answers* below.
216
216
  - `--continues ID` (with `--new`) starts the next link of that session's chain instead (see *Session chains*): in its folder, on its model (or the one `--model` names), LLM context, thinking level, toolkit, bundle settings and parent answers, so `--dir`, `--llm-context*`, `--thinking`, `--toolkit`, `--tool`, `--no-tool`, `--set` and `--parent-answers` are refused beside it; `ID` may be a prefix or `last:ID`, the chain's latest link. Without a message the new link starts idle; `--wait` then has nothing to wait for (a usage error). It prints `<full id> started (continues 3fa2c1d0)`, with `; 2 delegates moved` inside the parentheses when open delegates moved to it; a refusal (continued already, naming the next link; an open delegate that can't move; a turn running) is `chi send: refused: …`, exit 1, and a `--model` it can't start on is `chi send: could not start a session: …`, exit 1, nothing archived. A fallback to the default model (below) prints `chi send: warning: …`.
217
217
  - The 16 KiB cap applies: `git diff | chi send --new …` on a big diff is refused; name the branch in the message instead and let the session read it.
@@ -84,8 +84,8 @@ module Samagotchi
84
84
  # @param on_exit_request [#call, nil] a client asks the worker to exit
85
85
  # now: takes the client_id and delete: (the exit is to delete the
86
86
  # session, /exit --delete), returns nil when the worker will leave or
87
- # the Symbol that keeps it up (WorkerIdleExit#hold_for_request); called
88
- # with the event log held. Without one, POST /exit answers 501
87
+ # what keeps it up (a WorkerIdleExit::Hold: #reason, #tasks, #hint);
88
+ # called with the event log held. Without one, POST /exit answers 501
89
89
  # @param exit_discards [#call, nil] after an exit the worker agreed to:
90
90
  # whether it will delete the session as empty (the 200 says
91
91
  # +discard+); without one the reply leaves the field out
@@ -823,15 +823,15 @@ module Samagotchi
823
823
  deadline = fetched(parsed, "deadline")
824
824
  return BAD_DEADLINE unless deadline_valid?(deadline)
825
825
 
826
- reason = @engine.synchronize_events do
826
+ hold = @engine.synchronize_events do
827
827
  raise IntakeClosed if stopped?
828
828
  next :expired if expired?("exit_expired", deadline, sid: session_id, client_id: client_id)
829
829
 
830
830
  @on_exit_request.call(client_id, **options)
831
831
  end
832
- return deadline_passed("exit request") if reason == :expired
832
+ return deadline_passed("exit request") if hold == :expired
833
833
 
834
- if reason.nil?
834
+ if hold.nil?
835
835
  return [{}, 200, { status: "restarting", session_id: @session_id }] if restart
836
836
 
837
837
  body = { status: "exiting", session_id: @session_id }
@@ -839,10 +839,9 @@ module Samagotchi
839
839
  return [{}, 200, body]
840
840
  end
841
841
 
842
- # A hold may name what it waits for ({reason:, tasks:}: the background
843
- # tasks a finish wake watches).
844
- held = reason.is_a?(Hash) ? reason : { reason: reason }
845
- [{}, 409, { status: "held", reason: held[:reason].to_s, tasks: held[:tasks], hint: held[:hint],
842
+ # A hold may name what it waits for (tasks: the background tasks a
843
+ # finish wake watches).
844
+ [{}, 409, { status: "held", reason: hold.reason.to_s, tasks: hold.tasks, hint: hold.hint,
846
845
  session_id: @session_id }.compact]
847
846
  end
848
847
 
@@ -8,6 +8,7 @@ require_relative "../memory_bundle/shas"
8
8
  require_relative "../memory_bundle/memory_files"
9
9
  require_relative "../plugin/api"
10
10
  require_relative "../version"
11
+ require_relative "../cli/flags"
11
12
 
12
13
  module Samagotchi
13
14
  class BundleCommand
@@ -23,6 +24,22 @@ module Samagotchi
23
24
  # sha256 lines (MemoryBundle::Shas). #run returns 0 without errors, 1
24
25
  # with any.
25
26
  class Check
27
+ HELP = <<~TEXT
28
+ Usage: chi bundle check [PATH] [--fix] [--set KEY=VALUE]
29
+
30
+ Check the bundle at PATH (default: .) as an install would take it, one finding per line:
31
+ error|warn|info CODE file[:line]: message (fix: hint)
32
+ It installs and loads the bundle in a sandbox (temp HOME, config and state), not in yours, but its plugin and
33
+ hooks run in this process as written: run it on code you'd install.
34
+ --fix rewrite stale and placeholder sha256 lines in manifest.yml
35
+ --set KEY=VALUE a setting for the load (config.yml bundles: <name>: KEY), repeatable
36
+ Exit status: 0 no errors, 1 errors, 2 usage.
37
+ TEXT
38
+ FLAGS = CLI::Flags.new(help: %w[--help], flag_pattern: /\A--/) do |f|
39
+ f.switch "--fix"
40
+ f.value "--set", key: :set, repeat: true
41
+ end
42
+
26
43
  Finding = Data.define(:level, :code, :file, :line, :message, :fix) do
27
44
  def error? = level == :error
28
45
 
@@ -234,13 +251,26 @@ module Samagotchi
234
251
  # A shipped bundle installed from any chi's copy is that bundle.
235
252
  return if shipped?
236
253
 
237
- record = MemoryBundle::Provenance.new(name: name).record
238
- return unless record && File.expand_path(record.source.to_s) != @dir
254
+ record = installed_record(name)
255
+ return unless record
256
+ return unreadable_clash(name, record.error) if record.error
257
+ return if File.expand_path(record.source.to_s) == @dir
239
258
 
240
259
  add(:warn, :clash, "manifest.yml", "a bundle named #{name} is installed from #{record.source}",
241
260
  line: manifest_line("name"), fix: "rename the bundle, or chi bundle upgrade #{display(@dir)} to replace it")
242
- rescue StandardError
243
- nil
261
+ end
262
+
263
+ # The installed same-named bundle's record; an unreadable one as
264
+ # InstalledBundle.unreadable.
265
+ def installed_record(name)
266
+ MemoryBundle::Provenance.new(name: name).record
267
+ rescue JSON::ParserError, SystemCallError => e
268
+ MemoryBundle::InstalledBundle.unreadable(name, "#{e.class}: #{e.message.lines.first&.strip}")
269
+ end
270
+
271
+ def unreadable_clash(name, error)
272
+ add(:warn, :clash, "manifest.yml", "a bundle named #{name} is installed, but its record can't be read (#{error})",
273
+ line: manifest_line("name"), fix: "rename the bundle, or chi bundle install --force #{display(@dir)} to replace it")
244
274
  end
245
275
 
246
276
  # An unfilled `sha256: sha256:` isn't YAML: the Installer can't read
@@ -303,19 +333,20 @@ module Samagotchi
303
333
 
304
334
  def report_registered(manifest, registered)
305
335
  plugin = manifest.plugin ? manifest.plugin[:file] : "manifest.yml"
306
- registered[:commands].each { |name, _, _| add(:info, :registered, plugin, "command #{name}") }
307
- registered[:tools].each { |name| add(:info, :registered, plugin, "tool #{name}") }
308
- registered[:hooks].each do |event, hooks|
309
- hooks.each do |_bundle, hook, priority|
310
- file = manifest.hooks.key?(hook) ? "hooks/#{hook}" : plugin
311
- next add(:info, :registered, file, "hook #{event} (priority #{priority})") if Hooks::EVENTS.include?(event)
336
+ registered.commands.each { |command| add(:info, :registered, plugin, "command #{command.name}") }
337
+ registered.tools.each { |name| add(:info, :registered, plugin, "tool #{name}") }
338
+ registered.hooks.each do |event, hooks|
339
+ hooks.each do |hook|
340
+ file = manifest.hooks.key?(hook.hook) ? "hooks/#{hook.hook}" : plugin
341
+ next add(:info, :registered, file, "hook #{event} (priority #{hook.priority})") if Hooks::EVENTS.include?(event)
312
342
 
313
343
  add(:warn, :"hook-event", file, "hook on #{event.inspect}, which chi never fires",
314
344
  fix: "one of #{Hooks::EVENTS.join(", ")}")
315
345
  end
316
346
  end
317
- { inits: "init", toolkits: "toolkit", tool_sources: "tool source", peer_sources: "peer source" }.each do |key, what|
318
- registered[key].each { |name| add(:info, :registered, plugin, "#{what} #{name}") }
347
+ { "init" => registered.inits, "toolkit" => registered.toolkits, "tool source" => registered.tool_sources,
348
+ "peer source" => registered.peer_sources }.each do |what, names|
349
+ names.each { |name| add(:info, :registered, plugin, "#{what} #{name}") }
319
350
  end
320
351
  end
321
352
 
@@ -3,6 +3,7 @@
3
3
  require "fileutils"
4
4
  require_relative "../memory_bundle/shas"
5
5
  require_relative "../version"
6
+ require_relative "../cli/flags"
6
7
 
7
8
  module Samagotchi
8
9
  class BundleCommand
@@ -12,6 +13,17 @@ module Samagotchi
12
13
  # Minitest test on the kit that passes as written, and a README. The
13
14
  # test is the pattern to copy (docs/bundle-authoring.md).
14
15
  class Scaffold
16
+ HELP = <<~TEXT
17
+ Usage: chi bundle new NAME [--dir DIR]
18
+
19
+ Start a bundle in DIR/NAME (default ./NAME; refused when it exists): manifest.yml (shas filled,
20
+ requires_chi this chi), plugin.rb (a /NAME command and an after_tool_call hook), test/NAME_test.rb
21
+ (passes as written) and README.md. Then: chi bundle test, chi bundle check, chi bundle install.
22
+ TEXT
23
+ FLAGS = CLI::Flags.new(help: %w[--help], flag_pattern: /\A--/) do |f|
24
+ f.value "--dir"
25
+ end
26
+
15
27
  # A name that is also a slash command (Plugin::Api::COMMAND_NAME).
16
28
  NAME = /\A[a-z][a-z0-9_-]{0,31}\z/
17
29
 
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "rbconfig"
4
+ require_relative "../cli/flags"
4
5
 
5
6
  module Samagotchi
6
7
  class BundleCommand
@@ -15,6 +16,17 @@ module Samagotchi
15
16
  # (a checkout or a vendored install: its gems in vendor/bundle), there.
16
17
  # The tests' exit status is #run's.
17
18
  class TestRun
19
+ HELP = <<~TEXT
20
+ Usage: chi bundle test [PATH] [-- ARGS]
21
+
22
+ Run the tests of the bundle at PATH (default: .) on the Ruby and the lib chi runs on, outside any Bundler env:
23
+ test/**/*_test.rb on Minitest (require "samagotchi/testing/minitest"), or else spec/ on RSpec with the kit
24
+ (-r samagotchi/testing/rspec). ARGS go to the test runner (-- -n /name/, -- -e "a name").
25
+ The tests run the bundle's code as written, with your HOME (the kit's sandbox is per test): run code you'd install.
26
+ Exit status: the tests'; 1 no tests; 2 usage, or minitest / rspec doesn't load.
27
+ TEXT
28
+ FLAGS = CLI::Flags.new(help: %w[--help], flag_pattern: /\A-/)
29
+
18
30
  LIB_DIR = File.expand_path("../..", __dir__)
19
31
 
20
32
  def initialize(dir, args: [], stdout: $stdout, stderr: $stderr)
@@ -0,0 +1,164 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../cli/exit"
4
+ require_relative "../../cli/flags"
5
+ require_relative "../../bundle_session_settings"
6
+ require_relative "../../thinking"
7
+ require_relative "sandbox"
8
+ require_relative "run"
9
+ require_relative "trace"
10
+ require_relative "render"
11
+
12
+ module Samagotchi
13
+ class BundleCommand
14
+ module Try
15
+ # `chi bundle try PATH -p TEXT [options]` (docs/cli.md, "Trying a
16
+ # bundle"): checks the arguments, then installs PATH in a Sandbox, runs
17
+ # one turn (Run), stops what the run left (Sandbox#stop_leftovers),
18
+ # reads its Trace and prints it (Render). BundleCommand parses the
19
+ # flags (FLAGS, HELP) and hands the result to #run.
20
+ class Command
21
+ HELP = <<~TEXT
22
+ Usage: chi bundle try PATH -p TEXT [--model NAME] [--memory NAME] [--mute NAME] [--toolkit NAME]
23
+ [--thinking LEVEL] [--set KEY=VALUE] [--json] [--keep] [--timeout SECONDS]
24
+
25
+ Install PATH and run one non-interactive turn in an isolated temporary config, state and work directory.
26
+ The user's hosts, keys and ordinary runtime settings are retained; their bundles, hooks, guardrails,
27
+ memories, prompt additions, sessions and attached context sources are not. Shipped guardrails and a
28
+ $1 cost cap are installed for the run. --set KEY=VALUE sets the tried bundle's config.yml bundles entry;
29
+ --set cost-cap.cap=N overrides the cap (unlike chi --set BUNDLE.KEY=VALUE, these are config settings).
30
+ --memory and --mute accept comma-separated names and repeat. --keep retains the sandbox and debug log.
31
+ --json prints the experimental machine-readable trace.
32
+ Exit status: child turn's status; 1 on install failure or timeout; 2 for usage; 130 on Ctrl-C.
33
+ TEXT
34
+ FLAGS = CLI::Flags.new(help: %w[--help], flag_pattern: /\A-/) do |f|
35
+ f.value "-p", "--prompt", key: :prompt
36
+ f.value "--model"
37
+ f.value "--memory", repeat: true
38
+ f.value "--mute", repeat: true
39
+ f.value "--toolkit"
40
+ f.value "--thinking"
41
+ f.value "--set", repeat: true
42
+ f.switch "--json"
43
+ f.switch "--keep"
44
+ f.value "--timeout"
45
+ f.refuse "--attach", "--shared", "chi bundle try can't use --attach or --shared"
46
+ end
47
+ DEFAULT_TIMEOUT = 300
48
+ # The sandbox's cost-cap bundle setting (--set cost-cap.cap=N).
49
+ COST_CAP_KEY = "cost-cap.cap"
50
+ DEFAULT_COST_CAP = 1
51
+ # The tried bundle's --set values, and the cap for the run.
52
+ Settings = Data.define(:bundle, :cost_cap, :cost_cap_override)
53
+
54
+ def initialize(stdout:, stderr:)
55
+ @stdout = stdout
56
+ @stderr = stderr
57
+ end
58
+
59
+ # @param parsed [CLI::Flags::Result] FLAGS' parse of the arguments
60
+ # @return [Integer] exit status
61
+ def run(parsed)
62
+ options = parsed.options
63
+ path = checked_path(parsed) or return CLI::Exit::USAGE
64
+ timeout = parse_timeout(options[:timeout]) or return CLI::Exit::USAGE
65
+ settings = parse_settings(Array(options[:set])) or return CLI::Exit::USAGE
66
+
67
+ try(path, options, timeout, settings)
68
+ end
69
+
70
+ private
71
+
72
+ def try(path, options, timeout, settings)
73
+ render = Render.new(stdout: @stdout, stderr: @stderr)
74
+ sandbox = nil
75
+ begin
76
+ sandbox = Sandbox.new(path, bundle_settings: settings.bundle, cost_cap: settings.cost_cap,
77
+ cost_cap_override: settings.cost_cap_override)
78
+ sandbox.install
79
+ result = Run.new(sandbox).run(prompt: options[:prompt], options: options, timeout: timeout)
80
+ # Before the trace: a delegate's worker saves its session as it stops.
81
+ sandbox.stop_leftovers
82
+ trace = TraceReader.new(state_home: sandbox.state_home, session_id: result.session_id)
83
+ .read(exit_code: result.exit_status, answer: result.stdout, stderr: result.stderr,
84
+ sandbox: options[:keep] ? sandbox.root : nil, timed_out: result.timed_out)
85
+ render.trace(trace, json: options[:json], child_stderr: result.stderr)
86
+ @stderr.puts "chi bundle try: timed out after #{timeout} seconds" if result.timed_out
87
+ result.exit_status
88
+ rescue Sandbox::Error => e
89
+ @stderr.puts e.message
90
+ e.status
91
+ ensure
92
+ if options[:keep] && sandbox
93
+ sandbox.stop_leftovers
94
+ render.sandbox(sandbox)
95
+ end
96
+ sandbox&.cleanup unless options[:keep]
97
+ end
98
+ end
99
+
100
+ # @return [String, nil] PATH, or nil after saying what's wrong
101
+ def checked_path(parsed)
102
+ options = parsed.options
103
+ if options[:prompt].nil? || parsed.args.size != 1
104
+ @stderr.puts "Usage: chi bundle try PATH -p TEXT [options]"
105
+ return nil
106
+ end
107
+ path = parsed.args.first
108
+ unless File.directory?(path)
109
+ @stderr.puts "chi bundle try: #{path} isn't a folder"
110
+ return nil
111
+ end
112
+ if options.values_at(:model, :toolkit, :thinking, :memory, :mute).flatten.compact.any?(&:empty?)
113
+ @stderr.puts "chi bundle try: model, toolkit, thinking, memory and mute values cannot be empty"
114
+ return nil
115
+ end
116
+ if options[:thinking] && !Thinking::LEVELS.map(&:to_s).include?(options[:thinking])
117
+ @stderr.puts "chi bundle try: --thinking takes #{Thinking::LEVELS.join(", ")}, not #{options[:thinking]}"
118
+ return nil
119
+ end
120
+ path
121
+ end
122
+
123
+ def parse_timeout(value)
124
+ return DEFAULT_TIMEOUT unless value
125
+
126
+ timeout = Float(value)
127
+ return timeout if timeout.positive? && timeout.finite?
128
+
129
+ @stderr.puts "chi bundle try: --timeout must be a positive number"
130
+ nil
131
+ rescue ArgumentError
132
+ @stderr.puts "chi bundle try: --timeout must be a positive number"
133
+ nil
134
+ end
135
+
136
+ # The --set KEY=VALUE pairs, typed as BundleSessionSettings.typed:
137
+ # cost-cap.cap is the run's cap, the others the tried bundle's.
138
+ # @return [Settings, nil] nil after saying what's wrong
139
+ def parse_settings(pairs)
140
+ bundle = {}
141
+ cost_cap = DEFAULT_COST_CAP
142
+ override = false
143
+ pairs.each do |pair|
144
+ key, sep, value = pair.partition("=")
145
+ if key == COST_CAP_KEY && !sep.empty?
146
+ cost_cap = BundleSessionSettings.typed(value)
147
+ override = true
148
+ next if (cost_cap.is_a?(Numeric) && cost_cap >= 0) || cost_cap == false
149
+
150
+ @stderr.puts "chi bundle try: --set #{COST_CAP_KEY} takes a non-negative number or off"
151
+ return nil
152
+ end
153
+ unless !sep.empty? && key.match?(BundleSessionSettings::KEY)
154
+ @stderr.puts "chi bundle try: --set takes KEY=VALUE, not #{pair}"
155
+ return nil
156
+ end
157
+ bundle[key] = BundleSessionSettings.typed(value)
158
+ end
159
+ Settings.new(bundle: bundle, cost_cap: cost_cap, cost_cap_override: override)
160
+ end
161
+ end
162
+ end
163
+ end
164
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Samagotchi
6
+ class BundleCommand
7
+ module Try
8
+ # What `chi bundle try` prints of a run: the trace's text lines (on
9
+ # stdout, or on stderr under the --json report) and --keep's paths.
10
+ class Render
11
+ def initialize(stdout:, stderr:)
12
+ @stdout = stdout
13
+ @stderr = stderr
14
+ end
15
+
16
+ # The child's stderr (without its Session: line), then the trace.
17
+ def trace(trace, json:, child_stderr:)
18
+ error_lines = child_stderr.lines.reject { |line| line.start_with?("Session: ") }
19
+ @stderr.write(error_lines.join)
20
+ if json
21
+ lines(trace, @stderr, include_answer: false)
22
+ @stdout.puts JSON.generate(trace.to_h.transform_keys(&:to_s))
23
+ else
24
+ lines(trace, @stdout, include_answer: true)
25
+ end
26
+ end
27
+
28
+ def sandbox(sandbox)
29
+ @stderr.puts "sandbox: #{sandbox.root}"
30
+ @stderr.puts "debug log: #{File.join(sandbox.state_home, "samagotchi", "samagotchi.log")}"
31
+ end
32
+
33
+ def lines(trace, output, include_answer:)
34
+ output.puts "tools:"
35
+ trace.tools.each do |tool|
36
+ output.puts format(" %d %-16s %-7s %dms %s", tool[:index], tool[:name], tool[:status],
37
+ tool[:duration_ms], JSON.generate(tool[:args].to_s[0, 60]))
38
+ end
39
+ trace.notices.each { |notice| output.puts "notices: [#{notice["hook"] || "hook"}] #{notice["text"]}" }
40
+ trace.cards.each do |card|
41
+ output.puts "card: #{[card["title"], card["body"]].compact.join(" — ")}"
42
+ end
43
+ trace.questions.each do |entry|
44
+ question = entry.dig("pending_question", "question").to_s
45
+ outcome = if entry["cancelled"] && entry["reason"] == "non_interactive"
46
+ "unanswerable (non_interactive)"
47
+ elsif entry["cancelled"]
48
+ "cancelled (#{entry["reason"]})"
49
+ elsif entry["answer"]
50
+ "answered"
51
+ else
52
+ "unanswered"
53
+ end
54
+ output.puts "questions: #{JSON.generate(question)} -> #{outcome}"
55
+ end
56
+ if trace.interactive_blocked
57
+ count = trace.denied.size + trace.questions.count { |question| question["cancelled"] && question["reason"] == "non_interactive" }
58
+ output.puts "warn: #{count} question(s)/call(s) couldn't be answered"
59
+ end
60
+ if include_answer
61
+ answer_lines = trace.answer.lines
62
+ output.puts "answer:"
63
+ answer_lines.first(10).each { |line| output.puts " #{line.chomp}" }
64
+ output.puts " … (truncated)" if answer_lines.size > 10
65
+ end
66
+ tokens = trace.tokens
67
+ prompt = tokens[:prompt] || "unknown"
68
+ completion = tokens[:completion] || "unknown"
69
+ cost = if trace.cost
70
+ "#{"~" if trace.cost_is_estimate}$#{format("%.4f", trace.cost)}"
71
+ else
72
+ "unknown"
73
+ end
74
+ output.puts "tokens: #{prompt} in / #{completion} out cost #{cost} exit #{trace.exit_code}" \
75
+ "#{" (#{trace.session_id})" if trace.session_id}"
76
+ end
77
+ end
78
+ end
79
+ end
80
+ end