summaryrefslogtreecommitdiff
path: root/src/compaction.zig
blob: 4ec573228ff374d97397bafaf0016a8d2b29f12e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//! The builtin `/compact` slash command.
//!
//! Folds the conversation's older turns into a summary (via
//! `Agent.compact`), persists the result to the session log, and reports
//! the outcome to the user. Registered into the CLI's command registry by
//! `register`.

const std = @import("std");
const panto = @import("panto");
const command = @import("command.zig");

/// Install the `/compact` command into `registry`.
pub fn register(registry: *command.Registry) !void {
    try registry.register(.{
        .name = "compact",
        .description = "Summarize older turns to free up context. Optional args become extra compaction instructions.",
        .run = run,
    });
}

/// `/compact [extra instructions]` — compact the conversation now.
fn run(args: []const u8, ctx: *command.Context) anyerror!void {
    const extra: ?[]const u8 = if (args.len > 0) args else null;

    const res = ctx.agent.compactAndPersist(ctx.compaction_prompt, extra) catch |err| {
        try ctx.stdout.print("\n[compaction failed: {s}]\n> ", .{@errorName(err)});
        try ctx.stdout_file.flush();
        return;
    };

    if (res.compacted) {
        try ctx.stdout.print(
            "\n[compacted: summarized {d} message(s), kept {d} recent turn(s)]\n> ",
            .{ res.summarized_messages, res.kept_turns },
        );
    } else {
        try ctx.stdout.writeAll("\n[nothing to compact: conversation already fits]\n> ");
    }
    try ctx.stdout_file.flush();
}