@useavalon/caelence-agent 0.7.0 → 0.8.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.
package/README.md CHANGED
@@ -284,6 +284,8 @@ harness.close();
284
284
 
285
285
  `runTurn` streams `AgentEvent`s (text, tools, usage, errors) while it writes the session under `.harness/sessions`. Optional arguments include `config`, `mode`, `reasoningEffort`, `provider`, `extraTools`, `approvalPolicy`, and `observability`: pass a fake provider in tests, add MCP tools of your own through `extraTools`, and implement `approvalAsk` when a host UI needs to prompt for `exec` and `git_commit`. Hosts that call `constructOpenRouterProvider` can pass `reasoningEffort` there too, and `provider` to choose which OpenRouter hosts serve the model (for example `{ order: ["coreweave", "together"] }`, so a turn stays on fast hosts and keeps its prompt cache). `createConstructAgent({ contextManager })` can pass a Strands context strategy per turn; `Offload` and `ContextManagerStrategy` are re-exported so a host does not need its own copy of the SDK.
286
286
 
287
+ Compaction keeps one rolling summary: each new summary folds in the one before it (the summarizer gets it as `previousSummary`), and the checkpoint is marked `rolling`, so a long chat sends one summary rather than a list that grows with every compaction. A summarizer opts in by setting `foldsPreviousSummary = true` on the function (the default summarizer does); one that summarizes only its span keeps the summaries before it. A compaction covers only as many messages as fit the summarizer's input, and an empty summary leaves the session as it was. `compactionSummaries(session)` returns what the model is given. A host with its own session store can do the same: pass the current summary to its summarizer and set `rolling: true` on the checkpoint.
288
+
287
289
  If you only need types or tracing, `HarnessConfig` / `loadConfig` and the observability entry do not require constructing a harness at all.
288
290
 
289
291
  | Import | Use |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@useavalon/caelence-agent",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Caelence agent: Strands turn loop, local tools, skills, evals, and a themable terminal UI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -22,13 +22,14 @@ import { modePrompt } from "./mode.ts";
22
22
  import {
23
23
  compactionSummaries,
24
24
  DEFAULT_CONTEXT_WINDOW_TOKENS,
25
- isModelContextMessage,
26
25
  replaceUserTurn,
27
26
  type Session,
28
27
  type SessionMessage,
29
28
  type SessionStore,
29
+ SUMMARY_INPUT_CHARS,
30
30
  type SummarizerFn,
31
31
  sessionToProviderMessages,
32
+ summaryLine,
32
33
  titleFromUserMessage,
33
34
  } from "./session.ts";
34
35
  import type { AgentTool, ConstructAgent, ConstructedAgent } from "./strands.ts";
@@ -697,27 +698,36 @@ export function buildSystemPrompt(input: {
697
698
  return parts.join("\n\n");
698
699
  }
699
700
 
701
+ /** What the default summarizer is told; a rolling summary keeps what still holds. */
702
+ export const SUMMARIZER_PROMPT =
703
+ "Summarize this conversation in a few short paragraphs. Keep facts, decisions, preferences the person stated, and anything still open; drop what was settled and no longer matters. No preamble.";
704
+ export const ROLLING_SUMMARIZER_PROMPT =
705
+ "You keep one running summary of a conversation. Rewrite the summary so far to also cover the new turns, in a few short paragraphs. Keep facts, decisions, preferences the person stated, and anything still open; when a later turn changes something, keep the later version. No preamble.";
706
+
700
707
  export function defaultSummarizer(provider: MainModelProvider): SummarizerFn {
701
- return async ({ messages }) => {
702
- const text = messages
703
- .filter(isModelContextMessage)
704
- .map((m) => {
705
- if (m.kind === "turn") return `${m.role}: ${m.content}`;
706
- if (m.kind === "system") return `system: ${m.text}`;
707
- return `summary: ${m.summary}`;
708
- })
709
- .join("\n")
710
- .slice(0, 24_000);
708
+ const summarize: SummarizerFn = async ({ messages, previousSummary }) => {
709
+ const turns = messages
710
+ .map(summaryLine)
711
+ .filter((line): line is string => line !== null)
712
+ .join("\n");
713
+ // The store sends only what fits (see compactSession); the cut is a backstop.
714
+ const text = (
715
+ previousSummary ? `## Summary so far\n${previousSummary}\n\n## New turns\n${turns}` : turns
716
+ ).slice(0, SUMMARY_INPUT_CHARS);
711
717
  let out = "";
712
718
  for await (const event of provider.stream({
713
- system:
714
- "Summarize this conversation span in a few short paragraphs. Keep facts. No preamble.",
719
+ system: previousSummary ? ROLLING_SUMMARIZER_PROMPT : SUMMARIZER_PROMPT,
715
720
  messages: [{ role: "user", content: text }],
716
721
  maxTokens: 800,
717
722
  })) {
718
723
  if (event.type === "text_delta") out += event.text;
719
724
  if (event.type === "error") throw new Error(event.message);
720
725
  }
721
- return out.trim() || "Earlier turns were compacted.";
726
+ const summary = out.trim();
727
+ // An empty answer must not stand in for the conversation: fail the compaction.
728
+ if (!summary) throw new Error("the summarizer returned no text");
729
+ return summary;
722
730
  };
731
+ summarize.foldsPreviousSummary = true;
732
+ return summarize;
723
733
  }
@@ -2,13 +2,21 @@ import { describe, expect, test } from "bun:test";
2
2
  import { mkdtemp, rm } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
+ import type { MainModelProvider } from "./events.ts";
6
+ import { defaultSummarizer, ROLLING_SUMMARIZER_PROMPT } from "./run-turn.ts";
5
7
  import {
8
+ compactionSummaries,
6
9
  createFileSessionStore,
10
+ createMemorySessionStore,
7
11
  estimateTokens,
8
12
  latestCompactionCover,
9
13
  liveContextTokens,
10
14
  normalizeSessionTitle,
11
15
  replaceUserTurn,
16
+ type Session,
17
+ type SessionMessage,
18
+ SUMMARY_INPUT_CHARS,
19
+ type SummarizerFn,
12
20
  sessionToProviderMessages,
13
21
  sessionTranscript,
14
22
  titleFromUserMessage,
@@ -229,3 +237,154 @@ describe("session store", () => {
229
237
  }
230
238
  });
231
239
  });
240
+
241
+ describe("rolling compaction summaries", () => {
242
+ const checkpoint = (summary: string, to: number, rolling?: boolean): SessionMessage => ({
243
+ kind: "compaction_checkpoint",
244
+ summary,
245
+ coversFromSeq: 0,
246
+ coversToSeq: to,
247
+ ...(rolling ? { rolling: true } : {}),
248
+ });
249
+ const session = (messages: SessionMessage[]): Session => ({
250
+ id: "s",
251
+ title: "t",
252
+ createdAt: "",
253
+ updatedAt: "",
254
+ messages,
255
+ });
256
+
257
+ test("without a rolling checkpoint every summary is kept, as before", () => {
258
+ expect(compactionSummaries(session([checkpoint("a", 1), checkpoint("b", 3)]))).toEqual([
259
+ "a",
260
+ "b",
261
+ ]);
262
+ });
263
+
264
+ test("a rolling checkpoint replaces every summary before it", () => {
265
+ const s = session([checkpoint("a", 1), checkpoint("b", 3, true), checkpoint("c", 5)]);
266
+ expect(compactionSummaries(s)).toEqual(["b", "c"]);
267
+ expect(
268
+ compactionSummaries(session([checkpoint("a", 1, true), checkpoint("ab", 3, true)])),
269
+ ).toEqual(["ab"]);
270
+ });
271
+
272
+ test("the store folds the summary so far into the next one and marks it rolling", async () => {
273
+ const store = createMemorySessionStore();
274
+ let s = await store.create("system");
275
+ const seen: Array<string | undefined> = [];
276
+ const summarize: SummarizerFn = async (input) => {
277
+ seen.push(input.previousSummary);
278
+ return `summary ${seen.length}`;
279
+ };
280
+ summarize.foldsPreviousSummary = true;
281
+ for (const round of [1, 2]) {
282
+ s = await store.append(s, {
283
+ kind: "turn",
284
+ role: "user",
285
+ content: `${round} ${"a".repeat(400)}`,
286
+ });
287
+ s = await store.append(s, { kind: "turn", role: "assistant", content: "b".repeat(400) });
288
+ s = await store.maybeCompact(s, 20, summarize);
289
+ }
290
+ expect(seen).toEqual([undefined, "summary 1"]);
291
+ const checkpoints = s.messages.filter((m) => m.kind === "compaction_checkpoint");
292
+ expect(checkpoints.every((m) => m.kind === "compaction_checkpoint" && m.rolling)).toBe(true);
293
+ expect(compactionSummaries(s)).toEqual(["summary 2"]);
294
+ });
295
+
296
+ test("a summarizer that does not fold the summary so far keeps the summaries before it", async () => {
297
+ const store = createMemorySessionStore();
298
+ let s = await store.create("system");
299
+ let n = 0;
300
+ for (const round of [1, 2]) {
301
+ s = await store.append(s, {
302
+ kind: "turn",
303
+ role: "user",
304
+ content: `${round} ${"a".repeat(400)}`,
305
+ });
306
+ s = await store.append(s, { kind: "turn", role: "assistant", content: "b".repeat(400) });
307
+ s = await store.maybeCompact(s, 20, async () => `span ${++n}`);
308
+ }
309
+ const rolling = s.messages.flatMap((m) =>
310
+ m.kind === "compaction_checkpoint" ? [m.rolling === true] : [],
311
+ );
312
+ // The first summary covers everything so far; the second only its own span.
313
+ expect(rolling).toEqual([true, false]);
314
+ expect(compactionSummaries(s)).toEqual(["span 1", "span 2"]);
315
+ });
316
+
317
+ test("only what fits the summarizer's input is covered; the rest waits for the next compaction", async () => {
318
+ const store = createMemorySessionStore();
319
+ let s = await store.create("system");
320
+ for (let i = 0; i < 4; i += 1) {
321
+ s = await store.append(s, {
322
+ kind: "turn",
323
+ role: i % 2 ? "assistant" : "user",
324
+ content: `${i}${"x".repeat(SUMMARY_INPUT_CHARS / 3)}`,
325
+ });
326
+ }
327
+ const read: string[][] = [];
328
+ const summarize: SummarizerFn = async ({ messages }) => {
329
+ read.push(messages.map((m) => (m.kind === "turn" ? (String(m.content)[0] ?? "") : m.kind)));
330
+ return `summary ${read.length}`;
331
+ };
332
+ summarize.foldsPreviousSummary = true;
333
+ s = await store.maybeCompact(s, 20, summarize);
334
+ const first = s.messages.find((m) => m.kind === "compaction_checkpoint");
335
+ // The system message and two of the four turns fit; the other two are not marked as read.
336
+ expect(read[0]).toEqual(["system", "0", "1"]);
337
+ expect(first?.kind === "compaction_checkpoint" && first.coversToSeq).toBe(2);
338
+ s = await store.maybeCompact(s, 20, summarize);
339
+ expect(read[1]).toEqual(["2", "3"]);
340
+ expect(compactionSummaries(s)).toEqual(["summary 2"]);
341
+ });
342
+
343
+ test("an empty summary fails the compaction and keeps the session as it was", async () => {
344
+ const store = createMemorySessionStore();
345
+ let s = await store.create("system");
346
+ s = await store.append(s, { kind: "turn", role: "user", content: "a".repeat(400) });
347
+ const before = s.messages.length;
348
+ s = await store.maybeCompact(s, 20, async () => " ");
349
+ expect(s.messages.length).toBe(before);
350
+ const silent = {
351
+ kind: "fake",
352
+ modelId: "fake",
353
+ async *stream() {
354
+ yield { type: "done" };
355
+ },
356
+ } as unknown as MainModelProvider;
357
+ await expect(
358
+ defaultSummarizer(silent)({
359
+ session: s,
360
+ messages: s.messages,
361
+ coversFromSeq: 0,
362
+ coversToSeq: 1,
363
+ }),
364
+ ).rejects.toThrow("no text");
365
+ });
366
+
367
+ test("the default summarizer rewrites the summary so far with the new turns", async () => {
368
+ let asked: { system?: string; messages: Array<{ content: string }> } | undefined;
369
+ const provider = {
370
+ kind: "fake",
371
+ modelId: "fake",
372
+ async *stream(request: { system?: string; messages: Array<{ content: string }> }) {
373
+ asked = request;
374
+ yield { type: "text_delta", text: "rolled" };
375
+ yield { type: "done" };
376
+ },
377
+ } as unknown as MainModelProvider;
378
+ const out = await defaultSummarizer(provider)({
379
+ session: session([]),
380
+ messages: [{ kind: "turn", role: "user", content: "use teal" }],
381
+ coversFromSeq: 0,
382
+ coversToSeq: 0,
383
+ previousSummary: "built a pricing page",
384
+ });
385
+ expect(out).toBe("rolled");
386
+ expect(asked?.system).toBe(ROLLING_SUMMARIZER_PROMPT);
387
+ expect(asked?.messages[0]?.content).toContain("## Summary so far\nbuilt a pricing page");
388
+ expect(asked?.messages[0]?.content).toContain("user: use teal");
389
+ });
390
+ });
@@ -24,6 +24,12 @@ export type SessionMessage =
24
24
  summary: string;
25
25
  coversFromSeq: number;
26
26
  coversToSeq: number;
27
+ /**
28
+ * The summary covers the whole conversation up to `coversToSeq`, earlier
29
+ * summaries folded in, so it replaces every checkpoint before it in the
30
+ * prompt. Checkpoints without it cover only their own span.
31
+ */
32
+ rolling?: boolean;
27
33
  };
28
34
 
29
35
  export type ChatTranscriptLine =
@@ -54,9 +60,34 @@ export interface SummarizerInput {
54
60
  messages: SessionMessage[];
55
61
  coversFromSeq: number;
56
62
  coversToSeq: number;
63
+ /**
64
+ * The summary the model is given today (see {@link compactionSummaries}), to
65
+ * fold into the new one so it covers the whole conversation. Absent before
66
+ * the first compaction.
67
+ */
68
+ previousSummary?: string;
57
69
  }
58
70
 
59
- export type SummarizerFn = (input: SummarizerInput) => Promise<string>;
71
+ export interface SummarizerFn {
72
+ (input: SummarizerInput): Promise<string>;
73
+ /**
74
+ * The summarizer folds `previousSummary` into what it returns, so its summary
75
+ * can stand for the whole conversation (a `rolling` checkpoint). A summarizer
76
+ * without it summarizes only the span it is given, and its checkpoints keep
77
+ * the summaries before them.
78
+ */
79
+ foldsPreviousSummary?: boolean;
80
+ }
81
+
82
+ /** The longest text a summarizer is given: the summary so far plus the new turns. */
83
+ export const SUMMARY_INPUT_CHARS = 24_000;
84
+
85
+ /** One message as a summarizer reads it, or null for what it never sees. */
86
+ export function summaryLine(message: SessionMessage): string | null {
87
+ if (message.kind === "turn") return `${message.role}: ${message.content}`;
88
+ if (message.kind === "system") return `system: ${message.text}`;
89
+ return null;
90
+ }
60
91
 
61
92
  export function estimateTokens(messages: SessionMessage[]): number {
62
93
  let chars = 0;
@@ -145,20 +176,22 @@ export function sessionTranscript(session: Session): ChatTranscriptLine[] {
145
176
  return lines;
146
177
  }
147
178
 
179
+ /**
180
+ * The summaries the model is given, oldest first: from the last rolling
181
+ * checkpoint on (it already contains everything before it), or every
182
+ * checkpoint's summary when none is rolling. So a long chat carries one summary
183
+ * that is rewritten, not a list that grows with every compaction.
184
+ */
148
185
  export function compactionSummaries(session: Session): string[] {
149
- return session.messages
150
- .filter(
151
- (m): m is Extract<SessionMessage, { kind: "compaction_checkpoint" }> =>
152
- m.kind === "compaction_checkpoint",
153
- )
154
- .map((m) => m.summary);
155
- }
156
-
157
- function findLastCheckpointIndex(messages: SessionMessage[]): number {
158
- for (let i = messages.length - 1; i >= 0; i--) {
159
- if (messages[i]?.kind === "compaction_checkpoint") return i;
160
- }
161
- return -1;
186
+ const checkpoints = session.messages.filter(
187
+ (m): m is Extract<SessionMessage, { kind: "compaction_checkpoint" }> =>
188
+ m.kind === "compaction_checkpoint",
189
+ );
190
+ let from = 0;
191
+ checkpoints.forEach((checkpoint, i) => {
192
+ if (checkpoint.rolling) from = i;
193
+ });
194
+ return checkpoints.slice(from).map((m) => m.summary);
162
195
  }
163
196
 
164
197
  export interface SessionStore {
@@ -341,22 +374,55 @@ async function compactSession(
341
374
  ): Promise<Session> {
342
375
  const threshold = contextWindowTokens * COMPACTION_THRESHOLD_RATIO;
343
376
  if (liveContextTokens(session) < threshold) return session;
344
- const lastCheckpointIndex = findLastCheckpointIndex(session.messages);
345
- const coversFromSeq = lastCheckpointIndex + 1;
346
- const coversToSeq = session.messages.length - 1;
377
+ // Start right after what is already summarized (not after the newest
378
+ // checkpoint's position: a checkpoint may cover less than everything before it).
379
+ const coversFromSeq = latestCompactionCover(session) + 1;
380
+ const previous = compactionSummaries(session).join("\n\n");
381
+ // Cover only what fits the summarizer's input, so nothing is marked as
382
+ // summarized that it never read; the rest waits for the next compaction.
383
+ let budget = SUMMARY_INPUT_CHARS - (previous ? previous.length + 64 : 0);
384
+ let coversToSeq = coversFromSeq - 1;
385
+ for (let seq = coversFromSeq; seq < session.messages.length; seq += 1) {
386
+ const message = session.messages[seq];
387
+ const line = message && message.kind !== "compaction_checkpoint" ? summaryLine(message) : null;
388
+ const cost = line === null ? 0 : line.length + 1;
389
+ if (cost > budget && coversToSeq >= coversFromSeq) break;
390
+ budget -= cost;
391
+ coversToSeq = seq;
392
+ }
347
393
  if (coversFromSeq > coversToSeq) return session;
348
- const span = session.messages.slice(coversFromSeq, coversToSeq + 1);
394
+ const span = session.messages
395
+ .slice(coversFromSeq, coversToSeq + 1)
396
+ .filter((message) => message.kind !== "compaction_checkpoint");
397
+ if (span.length === 0) return session;
349
398
  let summary: string;
350
399
  try {
351
- summary = await summarize({ session, messages: span, coversFromSeq, coversToSeq });
400
+ summary = await summarize({
401
+ session,
402
+ messages: span,
403
+ coversFromSeq,
404
+ coversToSeq,
405
+ ...(previous ? { previousSummary: previous } : {}),
406
+ });
352
407
  } catch {
353
408
  return session;
354
409
  }
410
+ // No summary is a failed compaction: keep the session and its summaries as they are.
411
+ if (!summary.trim()) return session;
412
+ // Rolling when it stands for everything so far: the first summary always
413
+ // does; a later one only when the summarizer folded the previous one in.
414
+ const rolling = !previous || summarize.foldsPreviousSummary === true;
355
415
  return save({
356
416
  ...session,
357
417
  messages: [
358
418
  ...session.messages,
359
- { kind: "compaction_checkpoint", summary, coversFromSeq, coversToSeq },
419
+ {
420
+ kind: "compaction_checkpoint",
421
+ summary: summary.trim(),
422
+ coversFromSeq,
423
+ coversToSeq,
424
+ ...(rolling ? { rolling: true } : {}),
425
+ },
360
426
  ],
361
427
  });
362
428
  }
package/src/index.ts CHANGED
@@ -93,6 +93,7 @@ export {
93
93
  type TurnRequest,
94
94
  } from "./core/run-turn.ts";
95
95
  export {
96
+ compactionSummaries,
96
97
  createFileSessionStore,
97
98
  createMemorySessionStore,
98
99
  estimateTokens,
@@ -102,6 +103,8 @@ export {
102
103
  type Session,
103
104
  type SessionMessage,
104
105
  type SessionStore,
106
+ type SummarizerFn,
107
+ type SummarizerInput,
105
108
  sessionToProviderMessages,
106
109
  sessionTranscript,
107
110
  titleFromUserMessage,