@useavalon/caelence-agent 0.6.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 +3 -1
- package/package.json +1 -1
- package/src/core/run-turn.ts +24 -14
- package/src/core/session.test.ts +159 -0
- package/src/core/session.ts +86 -20
- package/src/core/strands.test.ts +34 -0
- package/src/core/strands.ts +31 -0
- package/src/index.ts +4 -0
package/README.md
CHANGED
|
@@ -282,7 +282,9 @@ await harness.runTurn("fix the failing test", (event) => {
|
|
|
282
282
|
harness.close();
|
|
283
283
|
```
|
|
284
284
|
|
|
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. `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.
|
|
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
|
+
|
|
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.
|
|
286
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
|
|
package/package.json
CHANGED
package/src/core/run-turn.ts
CHANGED
|
@@ -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
|
-
|
|
702
|
-
const
|
|
703
|
-
.
|
|
704
|
-
.
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
}
|
|
709
|
-
|
|
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
|
-
|
|
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
|
}
|
package/src/core/session.test.ts
CHANGED
|
@@ -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
|
+
});
|
package/src/core/session.ts
CHANGED
|
@@ -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
|
|
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
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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
|
-
|
|
345
|
-
|
|
346
|
-
const
|
|
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
|
|
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({
|
|
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
|
-
{
|
|
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/core/strands.test.ts
CHANGED
|
@@ -75,6 +75,40 @@ describe("constructOpenRouterProvider", () => {
|
|
|
75
75
|
expect(body.reasoning).toEqual({ effort: "high", exclude: false });
|
|
76
76
|
});
|
|
77
77
|
|
|
78
|
+
it("sends the provider routing it was given, and none by default", async () => {
|
|
79
|
+
const bodies: Array<{ provider?: unknown }> = [];
|
|
80
|
+
const realFetch = globalThis.fetch;
|
|
81
|
+
globalThis.fetch = (async (_url: unknown, init?: RequestInit) => {
|
|
82
|
+
if (typeof init?.body === "string") bodies.push(JSON.parse(init.body));
|
|
83
|
+
return new Response(JSON.stringify({ error: { message: "stop" } }), { status: 400 });
|
|
84
|
+
}) as unknown as typeof fetch;
|
|
85
|
+
try {
|
|
86
|
+
for (const provider of [
|
|
87
|
+
{ order: ["coreweave", "together"], allow_fallbacks: true },
|
|
88
|
+
undefined,
|
|
89
|
+
]) {
|
|
90
|
+
const model = constructOpenRouterProvider({
|
|
91
|
+
apiKey: "sk-test",
|
|
92
|
+
model: "deepseek/deepseek-v4.1-flash",
|
|
93
|
+
baseUrl: BASE_URL,
|
|
94
|
+
...(provider ? { provider } : {}),
|
|
95
|
+
});
|
|
96
|
+
for await (const _event of model.stream({
|
|
97
|
+
messages: [{ role: "user", content: "hi" }],
|
|
98
|
+
})) {
|
|
99
|
+
// drain
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
} finally {
|
|
103
|
+
globalThis.fetch = realFetch;
|
|
104
|
+
}
|
|
105
|
+
expect(bodies[0]?.provider).toEqual({
|
|
106
|
+
order: ["coreweave", "together"],
|
|
107
|
+
allow_fallbacks: true,
|
|
108
|
+
});
|
|
109
|
+
expect(bodies.at(-1)?.provider).toBeUndefined();
|
|
110
|
+
});
|
|
111
|
+
|
|
78
112
|
it("reports no usage before any request has completed", async () => {
|
|
79
113
|
const provider = constructOpenRouterProvider({
|
|
80
114
|
apiKey: "sk-test",
|
package/src/core/strands.ts
CHANGED
|
@@ -169,6 +169,30 @@ function wrapModelAsProvider(
|
|
|
169
169
|
};
|
|
170
170
|
}
|
|
171
171
|
|
|
172
|
+
/**
|
|
173
|
+
* OpenRouter provider routing: which hosts may serve a model, and in what order.
|
|
174
|
+
* Sent as the request's `provider` field. See
|
|
175
|
+
* https://openrouter.ai/docs/guides/routing/provider-selection
|
|
176
|
+
*/
|
|
177
|
+
export interface OpenRouterProviderRouting {
|
|
178
|
+
/** Hosts to try first, in this order (provider slugs such as `"together"`). */
|
|
179
|
+
order?: string[];
|
|
180
|
+
/** Whether other hosts may serve the request when the listed ones cannot. Defaults to true. */
|
|
181
|
+
allow_fallbacks?: boolean;
|
|
182
|
+
/** Only these hosts. */
|
|
183
|
+
only?: string[];
|
|
184
|
+
/** Never these hosts. */
|
|
185
|
+
ignore?: string[];
|
|
186
|
+
/** Rank hosts by price, throughput or latency instead of OpenRouter's default balancing. */
|
|
187
|
+
sort?: "price" | "throughput" | "latency";
|
|
188
|
+
/** Only hosts that support every parameter in the request. */
|
|
189
|
+
require_parameters?: boolean;
|
|
190
|
+
/** `"deny"` keeps prompts away from hosts that may store or train on them. */
|
|
191
|
+
data_collection?: "allow" | "deny";
|
|
192
|
+
/** Only hosts serving these quantizations (`"fp8"`, `"bf16"`, …). */
|
|
193
|
+
quantizations?: string[];
|
|
194
|
+
}
|
|
195
|
+
|
|
172
196
|
export function constructOpenRouterProvider(options: {
|
|
173
197
|
apiKey: string;
|
|
174
198
|
model: string;
|
|
@@ -179,6 +203,12 @@ export function constructOpenRouterProvider(options: {
|
|
|
179
203
|
sessionId?: () => string | undefined;
|
|
180
204
|
/** `X-Title` sent to OpenRouter, so usage can be told apart by purpose. Defaults to the product name. */
|
|
181
205
|
title?: string;
|
|
206
|
+
/**
|
|
207
|
+
* Which hosts serve this model. Pinning a short ordered list keeps the steps of
|
|
208
|
+
* one turn on the same host (and its prompt cache) and avoids slow hosts that
|
|
209
|
+
* OpenRouter's price-weighted default can pick.
|
|
210
|
+
*/
|
|
211
|
+
provider?: OpenRouterProviderRouting;
|
|
182
212
|
}): MainModelProvider {
|
|
183
213
|
if (!options.apiKey.trim()) {
|
|
184
214
|
return {
|
|
@@ -203,6 +233,7 @@ export function constructOpenRouterProvider(options: {
|
|
|
203
233
|
effort: options.reasoningEffort ?? DEFAULT_REASONING_EFFORT,
|
|
204
234
|
exclude: false,
|
|
205
235
|
},
|
|
236
|
+
...(options.provider ? { provider: options.provider } : {}),
|
|
206
237
|
},
|
|
207
238
|
clientConfig: {
|
|
208
239
|
baseURL: options.baseUrl.replace(/\/+$/, ""),
|
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,
|
|
@@ -116,6 +119,7 @@ export {
|
|
|
116
119
|
constructOpenRouterProvider,
|
|
117
120
|
createConstructAgent,
|
|
118
121
|
Offload,
|
|
122
|
+
type OpenRouterProviderRouting,
|
|
119
123
|
type StrandsBackedProvider,
|
|
120
124
|
} from "./core/strands.ts";
|
|
121
125
|
export { addUsage, formatUsage, parseTokenUsage, type TokenUsage } from "./core/usage.ts";
|