public inbox for kaagum@systemreboot.net
 help / color / mirror / Atom feed
From: Arun Isaac <arunisaac@systemreboot.net>
To: Arun Isaac <arunisaac@systemreboot.net>,
	Ricardo Wurmus <rekado@elephly.net>
Cc: kaagum@systemreboot.net
Subject: [PATCH v2 1/5] Support context compaction.
Date: Sun, 15 Nov 2026 04:47:46 +0000	[thread overview]
Message-ID: <20261115044752.5595-2-arunisaac@systemreboot.net> (raw)
In-Reply-To: <87ik20nycd.fsf@systemreboot.net>

---
 bin/kaagum            |  13 +++-
 kaagum/compacters.scm |  26 +++++++
 kaagum/tea.scm        | 176 ++++++++++++++++++++++++++++++------------
 3 files changed, 164 insertions(+), 51 deletions(-)
 create mode 100644 kaagum/compacters.scm

diff --git a/bin/kaagum b/bin/kaagum
index 2c8c9ee..50fbb76 100755
--- a/bin/kaagum
+++ b/bin/kaagum
@@ -24,6 +24,7 @@ exec guile --no-auto-compile -e main -s "$0" "$@"
              (srfi srfi-26)
              (srfi srfi-37)
              (ice-9 match)
+             (kaagum compacters)  ; for --compacter-eval expressions
              (kaagum config)
              (kaagum openai)
              (kaagum tea)
@@ -53,6 +54,9 @@ exec guile --no-auto-compile -e main -s "$0" "$@"
         (option (list #\t "more-tools") #t #f
                 (lambda (opt name arg result)
                   (acons 'more-tools arg result)))
+        (option (list #\c "compacter-eval") #t #f
+                (lambda (opt name arg result)
+                  (acons 'compacter-eval arg result)))
         (option (list "kagi-api-key-command") #t #f
                 (lambda (opt name arg result)
                   (acons 'kagi-api-key-command arg result)))
@@ -79,6 +83,7 @@ Run kaagum AI agent.
   -m, --model=MODEL              LLM model name to start new sessions with
                                  (default: \"anthropic/claude-opus-4.8\")
   -t, --more-tools=FILE          scheme file providing more tools to the agent
+  -c, --compacter-eval=EXPR      expression returning compacter (default: noop)
 
   --kagi-api-key-command=COMMAND command to run to get Kagi API key
 
@@ -112,7 +117,8 @@ Run kaagum AI agent.
                             invalid-option
                             invalid-argument
                             '((model . "anthropic/claude-opus-4.8")
-                              (api-base-uri . "https://openrouter.ai/api")))))
+                              (api-base-uri . "https://openrouter.ai/api")
+                              (compacter-eval . "noop-compacter")))))
        (when (assq-ref args 'help)
          (print-usage program)
          (exit #t))
@@ -135,7 +141,10 @@ Run kaagum AI agent.
                                       '())
                                   (if (assq-ref args 'more-tools)
                                       (load (assq-ref args 'more-tools))
-                                      '())))))
+                                      '()))
+                          (eval (call-with-input-string (assq-ref args 'compacter-eval)
+                                  read)
+                                (interaction-environment)))))
          (parameterize ((%kagi-api-key (and kagi-api-key-command
                                             (get-api-key kagi-api-key-command))))
            ;; (trace 'kagi "Key ~a" (%kagi-api-key))
diff --git a/kaagum/compacters.scm b/kaagum/compacters.scm
new file mode 100644
index 0000000..25a3281
--- /dev/null
+++ b/kaagum/compacters.scm
@@ -0,0 +1,26 @@
+;;; kaagum --- Tiny, security-focused AI agent in Guile
+;;; Copyright © 2026 Arun Isaac <arunisaac@systemreboot.net>
+;;;
+;;; This file is part of kaagum.
+;;;
+;;; kaagum is free software: you can redistribute it and/or modify it
+;;; under the terms of the GNU General Public License as published by
+;;; the Free Software Foundation, either version 3 of the License, or
+;;; (at your option) any later version.
+;;;
+;;; kaagum is distributed in the hope that it will be useful, but
+;;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;;; General Public License for more details.
+;;;
+;;; You should have received a copy of the GNU General Public License
+;;; along with kaagum.  If not, see <https://www.gnu.org/licenses/>.
+
+(define-module (kaagum compacters)
+  #:use-module (kaagum records)
+  #:export (noop-compacter))
+
+;; The noop compacter is an identity compacter. It doesn't compact at all; it
+;; returns the messages as they are.
+(define* (noop-compacter messages #:key tokens context-length #:allow-other-keys)
+  messages)
\ No newline at end of file
diff --git a/kaagum/tea.scm b/kaagum/tea.scm
index ca05f52..0ed8a32 100644
--- a/kaagum/tea.scm
+++ b/kaagum/tea.scm
@@ -67,11 +67,12 @@
                   #:key
                   (input-tokens 0) (output-tokens 0) (thought-tokens 0)
                   (cache-read-tokens 0) (cache-write-tokens 0) (cost 0)
-                  cancelling? (messages '()) (pending-tool-calls '())
-                  (allowed-tools '()) (rejected-tools '()))
+                  cancelling? (messages '()) (messages-context '())
+                  (pending-tool-calls '()) (allowed-tools '())
+                  (rejected-tools '()))
       (constructor cwd model input-tokens output-tokens thought-tokens
                    cache-read-tokens cache-write-tokens cost
-                   cancelling? messages pending-tool-calls
+                   cancelling? messages messages-context pending-tool-calls
                    allowed-tools rejected-tools)))
   (fields (cwd session-cwd lensed)
           (model session-model lensed)
@@ -89,6 +90,7 @@
           (cost session-cost lensed)
           (cancelling? session-cancelling? lensed)
           (messages session-messages lensed)
+          (messages-context session-messages-context lensed)
           (tool-calls session-tool-calls lensed)
           ;; List of tool names that are allowlisted for the session
           (allowed-tools session-allowed-tools lensed)
@@ -126,6 +128,24 @@ state."
            (key-ref session-id)
            state-sessions))
 
+(define (state-messages-context session-id)
+  "Return a lens to focus on the messages in the context of session with
+@var{session-id} in state."
+  (compose session-messages-context
+           (key-ref session-id)
+           state-sessions))
+
+(define (push-message session-id message state)
+  "Cons @var{message} onto both messages and the messages context of session with
+@var{session-id} in @var{state}."
+  (-> state
+      (push (state-messages session-id)
+            message
+            <>)
+      (push (state-messages-context session-id)
+            message
+            <>)))
+
 (define (state-tool-calls session-id)
   "Return a lens to focus on tool calls of session with @var{session-id} in state."
   (compose session-tool-calls
@@ -201,9 +221,11 @@ state."
            (key-ref session-id)
            state-sessions))
 
-(define (llm-requests session-id)
+(define (llm-requests session-id models)
   "Return the state-monadic list of @code{<llm-request>} objects for session with
-@var{session-id}."
+@var{session-id}.
+
+@var{models} is the same as in @code{tea-loop}."
   (state-let* ((state (current-state)))
     (state-return
      (if (and (null? (focus (state-tool-calls session-id)
@@ -211,17 +233,43 @@ state."
               (not (focus (state-session-cancelling? session-id)
                           state)))
          ;; There are no more tool calls in flight and a cancellation is not in
-         ;; progress; dispatch to LLM.
-         (list (llm-request session-id
-                            (focus (state-model session-id)
-                                   state)
-                            ;; Reverse because we have been prepending new
-                            ;; messages onto the list.
-                            (reverse (focus (state-messages session-id)
-                                            state))))
+         ;; progress; compact before dispatching to LLM.
+         (list (compaction-request
+                session-id
+                (focus (state-model session-id)
+                       state)
+                ;; Reverse because we have been prepending new messages onto
+                ;; this list.
+                (reverse (focus (state-messages-context session-id)
+                                state))
+                (+ (focus (state-session-input-tokens session-id)
+                          state)
+                   (focus (state-session-output-tokens session-id)
+                          state))
+                (focus (compose model-context-length
+                                (key-ref (focus (state-model session-id)
+                                                state)))
+                       models)))
          ;; There are tool calls or a cancellation in progress; do nothing.
          (list)))))
 
+(define (compaction-response-effects response)
+  (let ((session-id (compaction-response-session-id response)))
+    (state-begin
+     ;; Write compacted messages to state.
+     (state-let* ((state (current-state)))
+       (set-current-state (put (state-messages-context session-id)
+                               ;; Reverse because we want to keep prepending new
+                               ;; messages onto this list.
+                               (reverse (compaction-response-messages response))
+                               state))
+       ;; Dispatch compacted messages to LLM.
+       (state-return
+        (list (llm-request session-id
+                           (focus (state-model session-id)
+                                  state)
+                           (compaction-response-messages response))))))))
+
 (define-record-type* (<llm-request> llm-request llm-request?)
   (fields (session-id llm-request-session-id)
           (model llm-request-model)
@@ -239,6 +287,18 @@ state."
           (cost llm-response-cost)
           (http-error? llm-response-http-error?)))
 
+(define-record-type* (<compaction-request> compaction-request compaction-request?)
+  (fields (session-id compaction-request-session-id)
+          ;; Model name (string)
+          (model compaction-request-model)
+          (messages compaction-request-messages)
+          (tokens compaction-request-tokens)
+          (context-length compaction-request-context-length)))
+
+(define-record-type* (<compaction-response> compaction-response compaction-response?)
+  (fields (session-id compaction-response-session-id)
+          (messages compaction-response-messages)))
+
 (define-record-type* (<acp-message> acp-message acp-message?)
   (fields (json acp-message-json lensed)))
 
@@ -498,13 +558,13 @@ in @code{tea-loop}."
                  (else
                   (state-begin
                    (state-let* ((state (current-state)))
-                     (set-current-state (push (state-messages session-id)
-                                              ;; TODO: Allow more than one
-                                              ;; content block.
-                                              (user-message (focus (in-json 0 "text")
-                                                                   prompt))
-                                              state)))
-                   (llm-requests session-id))))))
+                     (set-current-state (push-message session-id
+                                                      ;; TODO: Allow more than
+                                                      ;; one content block.
+                                                      (user-message (focus (in-json 0 "text")
+                                                                           prompt))
+                                                      state)))
+                   (llm-requests session-id models))))))
              ("session/cancel"
               (let ((session-id (focus (in "params" "sessionId")
                                        request)))
@@ -665,10 +725,10 @@ session with @var{session-id}.
                   (state-let* ((state (current-state)))
                     (set-current-state (-> state
                                            ;; Push tool call response onto messages.
-                                           (push (state-messages session-id)
-                                                 (tool-message call-id
-                                                               (tool-call-parse-failure-message c))
-                                                 <>))))
+                                           (push-message session-id
+                                                         (tool-message call-id
+                                                                       (tool-call-parse-failure-message c))
+                                                         <>))))
                   ;; Notify client about invalid tool call.
                   (state-return (list (acp-message `(("jsonrpc" . "2.0")
                                                      ("method" . "session/update")
@@ -836,9 +896,9 @@ in @code{tea-loop}."
                                    (llm-response-cost response)
                                    <>)
                               ;; Push LLM response onto messages.
-                              (push (state-messages session-id)
-                                    llm-reply
-                                    <>))))
+                              (push-message session-id
+                                            llm-reply
+                                            <>))))
      (state-let* ((tool-call-effects
                    (state-append-map (lambda (call-json)
                                        (tool-call-effects session-id call-json tools))
@@ -859,25 +919,26 @@ in @code{tea-loop}."
                    ;; Else, return what we have so far.
                    (state-return effects)))
              ;; Maybe dispatch LLM requests.
-             (state-let* ((llm-requests (llm-requests session-id)))
+             (state-let* ((llm-requests (llm-requests session-id models)))
                (state-return (append effects llm-requests)))))))))
 
-(define (tool-call-result-effects result)
-  "Return the state-monadic list of effects for new tool call @var{result}."
+(define (tool-call-result-effects result models)
+  "Return the state-monadic list of effects for new tool call @var{result}.
+@var{models} is the same as in @code{tea-loop}."
   (let ((session-id (tool-call-result-session-id result)))
     (state-begin
      (state-let* ((state (current-state)))
        (set-current-state (-> state
                               ;; Push tool call result onto messages.
-                              (push (state-messages session-id)
-                                    (tool-call-result-message result)
-                                    <>)
+                              (push-message session-id
+                                            (tool-call-result-message result)
+                                            <>)
                               ;; Delete tool call from session tool call list.
                               (alist-delete-over (state-tool-calls session-id)
                                                  (tool-call-result-call-id result)
                                                  <>))))
      ;; Send a notification for each tool call evaluated.
-     (state-let* ((llm-requests (llm-requests session-id)))
+     (state-let* ((llm-requests (llm-requests session-id models)))
        (state-return
         (cons (acp-message `(("jsonrpc" . "2.0")
                              ("method" . "session/update")
@@ -933,9 +994,11 @@ in @code{tea-loop}."
    ((llm-response? message)
     (llm-response-effects message tools models))
    ((tool-call-result? message)
-    (tool-call-result-effects message))))
+    (tool-call-result-effects message models))
+   ((compaction-response? message)
+    (compaction-response-effects message))))
 
-(define* (tea-loop state llm-base-uri llm-api-key models tools
+(define* (tea-loop state llm-base-uri llm-api-key models tools compacter
                    #:optional (events (let ((line (get-line (current-input-port))))
                                         (and (not (eof-object? line))
                                              (begin
@@ -943,10 +1006,10 @@ in @code{tea-loop}."
                                                (list (acp-message (json-string->scm line))))))))
   "Run a @acronym{TEA, The Elm Architecture} loop starting with @var{state}.
 
-@var{llm-base-uri}, @var{llm-api-key} and @var{tools} are the same as in
-@code{run-tea-loop}. @var{models} is an association list mapping model IDs to
-@code{<model>} objects, the first element of which is the default model.
-@var{events} is an internal recursion variable."
+@var{llm-base-uri}, @var{llm-api-key}, @var{tools} and @var{compacter} are the
+same as in @code{run-tea-loop}. @var{models} is an association list mapping
+model IDs to @code{<model>} objects, the first element of which is the default
+model. @var{events} is an internal recursion variable."
   ;; Read a JSON-RPC message, handle it, and loop.
   (when events
     (let-values (((effects next-state)
@@ -954,18 +1017,18 @@ in @code{tea-loop}."
                     (state-append-map (cut acp-effects <> models tools)
                                       events)
                     state)))
-      (match (append-map (cut do-effect <> llm-base-uri llm-api-key tools)
+      (match (append-map (cut do-effect <> llm-base-uri llm-api-key tools compacter)
                          effects)
         (()
-         (tea-loop next-state llm-base-uri llm-api-key models tools))
+         (tea-loop next-state llm-base-uri llm-api-key models tools compacter))
         ((events ...)
-         (tea-loop next-state llm-base-uri llm-api-key models tools events))))))
+         (tea-loop next-state llm-base-uri llm-api-key models tools compacter events))))))
 
-(define (do-effect effect llm-base-uri llm-api-key tools)
+(define (do-effect effect llm-base-uri llm-api-key tools compacter)
   "Do @var{effect}. Return list of events produced by the effect.
 
-@var{llm-base-uri}, @var{llm-api-key} and @var{tools} are the same as in
-@code{run-tea-loop}."
+@var{llm-base-uri}, @var{llm-api-key}, @var{tools} and @var{compacter} are the
+same as in @code{run-tea-loop}."
   (cond
    ;; Send message to client, and return the state unchanged.
    ((acp-message? effect)
@@ -1019,20 +1082,35 @@ in @code{tea-loop}."
                                          json)
                                   0)
                               #f)))))
+   ;; Send messages to compacter for compaction; trace this if the messages were
+   ;; actually compacted.
+   ((compaction-request? effect)
+    (list (compaction-response
+           (compaction-request-session-id effect)
+           (compacter (compaction-request-messages effect)
+                      #:tokens (compaction-request-tokens effect)
+                      #:context-length (compaction-request-context-length effect)
+                      #:llm-base-uri llm-base-uri
+                      #:llm-api-key llm-api-key
+                      #:model (compaction-request-model effect)))))
    ;; Evaluate tool, handle the result, and return the new state.
    ((tool-call? effect)
     (list (eval-tool-call effect tools)))))
 
-(define (run-tea-loop llm-base-uri llm-api-key model tools)
+(define (run-tea-loop llm-base-uri llm-api-key model tools compacter)
   "Run a @acronym{TEA, The Elm Architecture} loop. @var{llm-base-uri} is the base
 URI of the LLM provider. @var{llm-api-key} is the API key to authenticate with
 the LLM provider. @var{model} is the name of the model to initialize sessions
 with. @var{tools} is the list of tools made available to the LLM. It is an
-association list matching tool names to @code{<tool>} objects."
+association list matching tool names to @code{<tool>} objects. @var{compacter}
+is a function that takes a list of messages and returns a compacted list of
+messages to query the LLM with. The compacted messages hopefully use fewer
+tokens than the original messages."
   (let ((models (openai-models llm-base-uri llm-api-key)))
     (tea-loop (state #f 0 0 '() '())
               llm-base-uri
               llm-api-key
               (cons (assoc model models)
                     (alist-delete model models))
-              tools)))
+              tools
+              compacter)))
-- 
2.54.0


  parent reply	other threads:[~2026-11-15  4:47 UTC|newest]

Thread overview: 29+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-06  8:11 strategies for context management Ricardo Wurmus
2026-11-06 14:21 ` Arun Isaac
2026-11-06 21:28   ` Ricardo Wurmus
2026-11-07  8:15     ` Ricardo Wurmus
2026-11-08  1:35       ` Arun Isaac
2026-11-08  1:36         ` [PATCH] Support context compaction Arun Isaac
2026-11-09 13:25         ` strategies for context management Ricardo Wurmus
2026-11-10 23:42           ` Arun Isaac
2026-11-13 22:41             ` [PATCH 1/4] Add message record equality comparators Arun Isaac
2026-11-13 22:41             ` [PATCH 2/4] Support context compaction Arun Isaac
2026-11-13 22:41             ` [PATCH 3/4] Add sliding window compacter Arun Isaac
2026-11-13 22:41             ` [PATCH 4/4] Allow loading compacter from file Arun Isaac
2026-11-13 22:46             ` strategies for context management Arun Isaac
2026-11-15  4:47               ` [PATCH v2 0/5] Context compaction Arun Isaac
2026-11-19 14:28                 ` Ricardo Wurmus
2026-11-19 14:29                   ` Ricardo Wurmus
2026-11-19 18:43                   ` Arun Isaac
2026-11-20  5:39                     ` Ricardo Wurmus
2026-11-20  5:56                       ` Ricardo Wurmus
2026-11-20 13:42                         ` Arun Isaac
2026-11-20 13:45                           ` Arun Isaac
2026-11-20 14:01                           ` Ricardo Wurmus
2026-11-22 16:54                             ` Arun Isaac
2026-11-15  4:47               ` Arun Isaac [this message]
2026-11-15  4:47               ` [PATCH v2 2/5] Add sliding window compacter Arun Isaac
2026-11-15  4:47               ` [PATCH v2 3/5] Add summarizing compacter Arun Isaac
2026-11-15  4:47               ` [PATCH v2 4/5] Document context compacters Arun Isaac
2026-11-15  4:47               ` [PATCH v2 5/5] Allow user-defined " Arun Isaac
2026-11-08  1:43     ` strategies for context management Arun Isaac

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261115044752.5595-2-arunisaac@systemreboot.net \
    --to=arunisaac@systemreboot.net \
    --cc=kaagum@systemreboot.net \
    --cc=rekado@elephly.net \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox