@operad-io/harness-pi 0.3.0 → 0.4.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/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@operad-io/harness-pi",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts"
7
7
  },
8
8
  "dependencies": {
9
- "@operad-io/access-match": "0.3.0",
10
- "@operad-io/engine": "0.3.0",
11
- "@operad-io/harness-process": "0.3.0",
12
- "@operad-io/mcp": "0.3.0"
9
+ "@operad-io/access-match": "0.4.0",
10
+ "@operad-io/engine": "0.4.0",
11
+ "@operad-io/harness-process": "0.4.0",
12
+ "@operad-io/mcp": "0.4.0"
13
13
  },
14
14
  "peerDependencies": {
15
15
  "@earendil-works/pi-coding-agent": "1.6.0"
package/src/index.ts CHANGED
@@ -463,6 +463,7 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
463
463
  let skills: readonly string[] = [];
464
464
  let ownSettings: unknown;
465
465
  let retry: unknown;
466
+ let compact: ReturnType<typeof compactOf>;
466
467
  let images: ReturnType<typeof imageInputsOf> = [];
467
468
 
468
469
  const step = await readAgentStep(ctx, params, {
@@ -530,6 +531,7 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
530
531
  if (retry !== undefined && typeof retry !== "boolean") {
531
532
  throw new Error(`${at}: params.retry: must be a boolean`);
532
533
  }
534
+ compact = compactOf(read.input.compact, `${at}: params.compact`);
533
535
  images = imageInputsOf(read.input.images ?? read.flow.images);
534
536
  },
535
537
  });
@@ -563,6 +565,7 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
563
565
  ...(skills.length === 0 ? {} : { skills }),
564
566
  ...(ownSettings === true ? { useOwnSettings: true } : {}),
565
567
  ...(retry === true ? { retry: true } : {}),
568
+ ...(compact === undefined ? {} : { compact }),
566
569
  ...(access.runAccess === undefined ? {} : { access: access.runAccess }),
567
570
  ...(access.secrets.length === 0 ? {} : { secretValues: access.secrets }),
568
571
  };
@@ -609,4 +612,30 @@ export function createPiHarnessPlugin(options: PiHarnessOptions = {}) {
609
612
  });
610
613
  }
611
614
 
615
+ /** The compaction a chat reply asks for (ADR 0023 D12), checked here so a bad value fails the step by name. */
616
+ function compactOf(
617
+ value: unknown,
618
+ at: string,
619
+ ): { at: number; flush?: string; now?: true; only?: true } | undefined {
620
+ if (value === undefined) return undefined;
621
+ if (!isRecord(value)) throw new Error(`${at}: must be an object`);
622
+ const share = value.at;
623
+ if (typeof share !== "number" || !Number.isFinite(share) || share <= 0 || share > 1) {
624
+ throw new Error(`${at}.at: must be a number above 0 and at most 1`);
625
+ }
626
+ const flush = value.flush;
627
+ if (flush !== undefined && typeof flush !== "string") throw new Error(`${at}.flush: must be a string`);
628
+ for (const field of ["now", "only"] as const) {
629
+ if (value[field] !== undefined && typeof value[field] !== "boolean") {
630
+ throw new Error(`${at}.${field}: must be a boolean`);
631
+ }
632
+ }
633
+ return {
634
+ at: share,
635
+ ...(flush === undefined || flush.length === 0 ? {} : { flush }),
636
+ ...(value.now === true ? { now: true as const } : {}),
637
+ ...(value.only === true ? { only: true as const } : {}),
638
+ };
639
+ }
640
+
612
641
  export default createPiHarnessPlugin();
package/src/protocol.ts CHANGED
@@ -64,6 +64,43 @@ export interface WorkerInput {
64
64
  readonly retry?: boolean | undefined;
65
65
  /** Set by a chat reply: the worker may serve the next reply and then end itself. */
66
66
  readonly keep?: WorkerKeep | undefined;
67
+ /** Set by a chat reply: compact the context when it nears the window (ADR 0023 D12). */
68
+ readonly compact?: WorkerCompact | undefined;
69
+ /** Overrides of the defaults for pruning old tool results (T-0767); pruning is on without it. */
70
+ readonly prune?: WorkerPrune | undefined;
71
+ }
72
+
73
+ /** What a run may change about pruning; each absent field keeps the default in `prune.ts`. */
74
+ export interface WorkerPrune {
75
+ /** Seconds since the last model message after which the prompt cache counts as expired. */
76
+ readonly cacheSecs?: number | undefined;
77
+ /** Assistant turns, counted from the last, whose tool results are kept. At least 1. */
78
+ readonly keepTurns?: number | undefined;
79
+ /** Characters of tool output a prune must free. */
80
+ readonly minChars?: number | undefined;
81
+ }
82
+
83
+ /** When and how a reply compacts the session's context. Without it pi never compacts. */
84
+ export interface WorkerCompact {
85
+ /** The share of the model's window, above 0 and at most 1, at which the context is compacted after a turn. */
86
+ readonly at: number;
87
+ /** The one silent turn run before a compaction; absent means compact without one. */
88
+ readonly flush?: string | undefined;
89
+ /** Compact after this turn whatever the context size. */
90
+ readonly now?: boolean | undefined;
91
+ /** Run no prompt: only the flush turn and the compaction. */
92
+ readonly only?: boolean | undefined;
93
+ }
94
+
95
+ /** What a compaction did, on the result line. */
96
+ export interface WorkerCompaction {
97
+ readonly reason: "threshold" | "manual";
98
+ /** The context before the compaction, in tokens. */
99
+ readonly before: number;
100
+ /** The estimated context after it, when pi could tell. */
101
+ readonly after?: number | undefined;
102
+ /** Whether the silent flush turn ran. */
103
+ readonly flushed: boolean;
67
104
  }
68
105
 
69
106
  export type FailureReason = "invalid_input" | "session_missing" | "model_missing" | "model_error";
@@ -77,6 +114,8 @@ export interface WorkerResult {
77
114
  /** The priced part of the run; `incomplete` when some message had no price. */
78
115
  readonly cost: { readonly micros: number; readonly incomplete?: true } | null;
79
116
  readonly finalMessage: string | null;
117
+ /** Set when this run compacted the session. */
118
+ readonly compaction?: WorkerCompaction | undefined;
80
119
  /** The context after the last model call, when one ran. */
81
120
  readonly context?: { readonly used: number; readonly window?: number } | undefined;
82
121
  readonly reason?: FailureReason;
@@ -97,6 +136,47 @@ export type WorkerLine =
97
136
  | { readonly type: "agent_settled"; readonly aborted: boolean }
98
137
  | WorkerResult;
99
138
 
139
+ function readCompact(
140
+ value: Readonly<Record<string, unknown>>,
141
+ ): { readonly ok: true; readonly value: WorkerCompact | undefined } | { readonly ok: false; readonly message: string } {
142
+ const found = value["compact"];
143
+ if (found === undefined) return { ok: true, value: undefined };
144
+ if (!isRecord(found)) return { ok: false, message: "compact must be an object" };
145
+ const at = found["at"];
146
+ if (typeof at !== "number" || !Number.isFinite(at) || at <= 0 || at > 1) {
147
+ return { ok: false, message: "compact.at must be a number above 0 and at most 1" };
148
+ }
149
+ const flush = found["flush"];
150
+ if (flush !== undefined && typeof flush !== "string") return { ok: false, message: "compact.flush must be a string" };
151
+ const now = found["now"];
152
+ if (now !== undefined && typeof now !== "boolean") return { ok: false, message: "compact.now must be a boolean" };
153
+ const only = found["only"];
154
+ if (only !== undefined && typeof only !== "boolean") return { ok: false, message: "compact.only must be a boolean" };
155
+ return { ok: true, value: { at, flush: flush === "" ? undefined : flush, now, only } };
156
+ }
157
+
158
+ function readPrune(
159
+ value: Readonly<Record<string, unknown>>,
160
+ ): { readonly ok: true; readonly value: WorkerPrune | undefined } | { readonly ok: false; readonly message: string } {
161
+ const found = value["prune"];
162
+ if (found === undefined) return { ok: true, value: undefined };
163
+ if (!isRecord(found)) return { ok: false, message: "prune must be an object" };
164
+ const number = (key: string, least: number): number | undefined | null => {
165
+ const raw = found[key];
166
+ if (raw === undefined) return undefined;
167
+ return typeof raw === "number" && Number.isFinite(raw) && raw >= least ? raw : null;
168
+ };
169
+ const cacheSecs = number("cacheSecs", 0);
170
+ if (cacheSecs === null) return { ok: false, message: "prune.cacheSecs must be a number, 0 or more" };
171
+ const keepTurns = number("keepTurns", 1);
172
+ if (keepTurns === null || (keepTurns !== undefined && !Number.isInteger(keepTurns))) {
173
+ return { ok: false, message: "prune.keepTurns must be a whole number, 1 or more" };
174
+ }
175
+ const minChars = number("minChars", 0);
176
+ if (minChars === null) return { ok: false, message: "prune.minChars must be a number, 0 or more" };
177
+ return { ok: true, value: { cacheSecs, keepTurns, minChars } };
178
+ }
179
+
100
180
  export type ParsedInput =
101
181
  | { readonly ok: true; readonly input: WorkerInput }
102
182
  | { readonly ok: false; readonly message: string };
@@ -159,6 +239,12 @@ export function parseInput(value: unknown): ParsedInput {
159
239
  const keep = readKeep(value);
160
240
  if (!keep.ok) return keep;
161
241
 
242
+ const compact = readCompact(value);
243
+ if (!compact.ok) return compact;
244
+
245
+ const prune = readPrune(value);
246
+ if (!prune.ok) return prune;
247
+
162
248
  return {
163
249
  ok: true,
164
250
  input: {
@@ -182,6 +268,8 @@ export function parseInput(value: unknown): ParsedInput {
182
268
  useOwnSettings: useOwnSettings.value,
183
269
  retry: retry.value,
184
270
  keep: keep.value,
271
+ compact: compact.value,
272
+ prune: prune.value,
185
273
  },
186
274
  };
187
275
  }
package/src/prune.ts ADDED
@@ -0,0 +1,135 @@
1
+ import { isRecord } from "@operad-io/engine";
2
+
3
+ /**
4
+ * Pruning old tool results from what a model call is sent (T-0767).
5
+ *
6
+ * pi's `context` hook gives each model call a deep copy of the transcript and
7
+ * sends what the hook returns, so the session file and what a person sees stay
8
+ * whole. This file is the decision and the rewrite; `worker.ts` registers it.
9
+ *
10
+ * Why a time rule: every prune rewrites the cached prefix of the prompt. While
11
+ * the provider's cache is alive a prune turns a cheap read into a write; once
12
+ * the cache has expired the whole prefix is rewritten anyway, so shrinking it
13
+ * is free. Why a size rule: a prune that frees little still pays the rewrite,
14
+ * so it waits until it frees enough.
15
+ */
16
+
17
+ /** What a prune needs; each has a documented default below. */
18
+ export interface PruneSettings {
19
+ /** The provider's prompt cache lifetime in ms: the model's own value, else `DEFAULT_CACHE_TTL_MS`. */
20
+ readonly ttlMs: number;
21
+ /** The most recent assistant turns whose tool results are never pruned. */
22
+ readonly keepTurns: number;
23
+ /** Prune only when it frees at least this many characters of tool output. */
24
+ readonly minChars: number;
25
+ }
26
+
27
+ /**
28
+ * The cache lifetime assumed when the model declares none: 5 minutes, the
29
+ * short tier of Anthropic's prompt cache and the conservative end of the
30
+ * providers' ranges.
31
+ */
32
+ export const DEFAULT_CACHE_TTL_MS = 5 * 60 * 1000;
33
+
34
+ /** The assistant turns kept whole, as OpenClaw's session pruning keeps three. */
35
+ export const DEFAULT_KEEP_TURNS = 3;
36
+
37
+ /**
38
+ * The least a prune must free, in characters of tool output (about 5,000
39
+ * tokens): the value Anthropic's context editing gives as its `clear_at_least`
40
+ * example. pi cuts a built-in tool's output to 2,000 lines or 50 KB (about
41
+ * 12,500 tokens) before it enters the context, so one result frees at most
42
+ * about 50,000 characters and this floor is two fifths of the largest; the
43
+ * tools operad adds (`operad_*`) are not cut by pi and may exceed that. Gemini
44
+ * CLI's 30,000-token floor would be larger than any one built-in result.
45
+ */
46
+ export const DEFAULT_MIN_PRUNE_CHARS = 20_000;
47
+
48
+ /** The text that stands in for a pruned result. */
49
+ export function placeholderFor(toolName: string): string {
50
+ return `[${toolName} result removed from the context to save space]`;
51
+ }
52
+
53
+ /** The characters of text a tool result holds; images and other blocks count nothing. */
54
+ function textLength(content: unknown): number {
55
+ if (!Array.isArray(content)) return 0;
56
+ let total = 0;
57
+ for (const block of content) {
58
+ if (isRecord(block) && block["type"] === "text" && typeof block["text"] === "string") total += block["text"].length;
59
+ }
60
+ return total;
61
+ }
62
+
63
+ function toolNameOf(message: Record<string, unknown>): string {
64
+ const name = message["toolName"];
65
+ return typeof name === "string" && name.length > 0 ? name : "tool";
66
+ }
67
+
68
+ /** The timestamp, in ms, of the last assistant message; undefined when there is none. */
69
+ export function lastAssistantAt(messages: readonly unknown[]): number | undefined {
70
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
71
+ const message = messages[i];
72
+ if (isRecord(message) && message["role"] === "assistant") {
73
+ const at = message["timestamp"];
74
+ return typeof at === "number" && Number.isFinite(at) ? at : undefined;
75
+ }
76
+ }
77
+ return undefined;
78
+ }
79
+
80
+ export interface PruneOutcome<M> {
81
+ readonly messages: readonly M[];
82
+ /** How many results were replaced. */
83
+ readonly pruned: number;
84
+ /** The characters of tool output the replacement frees. */
85
+ readonly freed: number;
86
+ }
87
+
88
+ /**
89
+ * The messages to send. Nothing is pruned while the cache is alive (`lastAt`
90
+ * within `ttlMs` of `now`; an unknown `lastAt` counts as alive), and nothing
91
+ * when the prune would free less than `minChars`. Otherwise every tool result
92
+ * older than the last `keepTurns` assistant messages and longer than its
93
+ * placeholder becomes the placeholder. The input is not changed.
94
+ */
95
+ export function pruneToolResults<M>(
96
+ messages: readonly M[],
97
+ settings: PruneSettings,
98
+ now: number,
99
+ lastAt: number | undefined,
100
+ ): PruneOutcome<M> {
101
+ const unchanged = { messages, pruned: 0, freed: 0 };
102
+ if (lastAt === undefined || now - lastAt <= settings.ttlMs) return unchanged;
103
+ // The index of the oldest of the kept assistant turns.
104
+ let seen = 0;
105
+ let boundary = 0;
106
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
107
+ const message = messages[i];
108
+ if (isRecord(message) && message["role"] === "assistant") {
109
+ seen += 1;
110
+ if (seen >= settings.keepTurns) {
111
+ boundary = i;
112
+ break;
113
+ }
114
+ }
115
+ }
116
+ if (seen < settings.keepTurns) return unchanged;
117
+ const replace = new Set<number>();
118
+ let freed = 0;
119
+ for (let i = 0; i < boundary; i += 1) {
120
+ const message = messages[i];
121
+ if (!isRecord(message) || message["role"] !== "toolResult") continue;
122
+ const saved = textLength(message["content"]) - placeholderFor(toolNameOf(message)).length;
123
+ if (saved <= 0) continue;
124
+ replace.add(i);
125
+ freed += saved;
126
+ }
127
+ if (replace.size === 0 || freed < settings.minChars) return unchanged;
128
+ const next = messages.map((message, i) => {
129
+ if (!replace.has(i) || !isRecord(message)) return message;
130
+ // The same message with its content replaced; the id, name and error flag stay.
131
+ const swapped: unknown = { ...message, content: [{ type: "text", text: placeholderFor(toolNameOf(message)) }] };
132
+ return swapped as M;
133
+ });
134
+ return { messages: next, pruned: replace.size, freed };
135
+ }
package/src/worker.ts CHANGED
@@ -45,10 +45,20 @@ import {
45
45
  type WorkerPorts,
46
46
  } from "@operad-io/harness-process";
47
47
  import { findPi, loadPi } from "./pi-install.ts";
48
+ import {
49
+ DEFAULT_CACHE_TTL_MS,
50
+ DEFAULT_KEEP_TURNS,
51
+ DEFAULT_MIN_PRUNE_CHARS,
52
+ lastAssistantAt,
53
+ pruneToolResults,
54
+ type PruneSettings,
55
+ } from "./prune.ts";
48
56
  import {
49
57
  DEFAULT_BASH_TIMEOUT_SECS,
50
58
  parseInput,
51
59
  type FailureReason,
60
+ type WorkerCompact,
61
+ type WorkerCompaction,
52
62
  type WorkerInput,
53
63
  type WorkerLine,
54
64
  type WorkerResult,
@@ -96,6 +106,8 @@ export interface WorkerHooks {
96
106
  registerProviders?(runtime: ModelRuntime): void;
97
107
  /** The clock for tool call times, in epoch milliseconds; the tests inject one. */
98
108
  now?: () => number;
109
+ /** The clock for the prune decision, apart from `now` so a reading here does not move the tool call times. */
110
+ pruneNow?: () => number;
99
111
  /** Sees the settings and loader options of one run; the tests use it. */
100
112
  observeResources?(seen: SeenResources): void;
101
113
  }
@@ -309,7 +321,29 @@ export async function runWorker(
309
321
  };
310
322
  // What a late answer continues; known once the session exists.
311
323
  let sessionFile: string | null = null;
324
+ // Old tool results leave what the model is sent once the prompt cache has
325
+ // expired (T-0767). pi's `context` hook gets a copy of the transcript and the
326
+ // session file is not touched. The time is `hooks.pruneNow` against the
327
+ // last model call this process made, else the last assistant message the
328
+ // session holds (a resumed session).
329
+ let lastModelCallAt: number | undefined;
330
+ const clock = hooks.pruneNow ?? Date.now;
312
331
  const operadExtension: ExtensionFactory = (pi) => {
332
+ pi.on("context", (event, ctx) => {
333
+ const promptCache = ctx.model?.promptCache;
334
+ const declared = process.env["PI_CACHE_RETENTION"] === "long" ? promptCache?.long : promptCache?.short;
335
+ const settings: PruneSettings = {
336
+ ttlMs: (input.prune?.cacheSecs ?? declared ?? DEFAULT_CACHE_TTL_MS / 1000) * 1000,
337
+ keepTurns: input.prune?.keepTurns ?? DEFAULT_KEEP_TURNS,
338
+ minChars: input.prune?.minChars ?? DEFAULT_MIN_PRUNE_CHARS,
339
+ };
340
+ const now = clock();
341
+ const outcome = pruneToolResults(event.messages, settings, now, lastModelCallAt ?? lastAssistantAt(event.messages));
342
+ lastModelCallAt = now;
343
+ if (outcome.pruned === 0) return undefined;
344
+ io.log(`pruned ${outcome.pruned} old tool results, ${outcome.freed} characters`);
345
+ return { messages: [...outcome.messages] };
346
+ });
313
347
  pi.on("tool_call", async (event) => {
314
348
  io.log(`tool_call ${event.toolName}`);
315
349
  if (event.toolName === "bash") {
@@ -507,23 +541,28 @@ export async function runWorker(
507
541
  const now = hooks.now ?? Date.now;
508
542
  const increments = new Increments(io, now, input.secretValues ?? []);
509
543
  const started = new Map<string, number>();
544
+ // Armed again for each prompt: the flush turn settles after the reply did.
510
545
  let settle: () => void = () => {};
511
- const settled = new Promise<void>((resolve) => {
512
- settle = resolve;
513
- });
546
+ const arm = (): Promise<void> =>
547
+ new Promise<void>((resolve) => {
548
+ settle = resolve;
549
+ });
550
+ let settled = arm();
551
+ // True while the silent flush turn runs: its words are not the reply's.
552
+ let quiet = false;
514
553
  session.subscribe((event) => {
515
554
  switch (event.type) {
516
555
  case "message_update": {
517
556
  const update = event.assistantMessageEvent;
518
557
  switch (update.type) {
519
558
  case "text_delta":
520
- increments.text(update.delta);
559
+ if (!quiet) increments.text(update.delta);
521
560
  break;
522
561
  case "thinking_delta":
523
- increments.thinking(update.delta);
562
+ if (!quiet) increments.thinking(update.delta);
524
563
  break;
525
564
  case "thinking_end":
526
- increments.endThinking(update.content);
565
+ if (!quiet) increments.endThinking(update.content);
527
566
  break;
528
567
  default:
529
568
  break;
@@ -531,9 +570,17 @@ export async function runWorker(
531
570
  break;
532
571
  }
533
572
  case "message_end": {
534
- if (event.message.role === "assistant") increments.endMessage(textOf(event.message.content, ""));
573
+ if (event.message.role === "assistant" && !quiet) increments.endMessage(textOf(event.message.content, ""));
535
574
  const line = tally.add(event.message);
536
- if (line !== undefined) io.line(line);
575
+ if (line !== undefined) {
576
+ // The flush turn's usage and price count; its text does not show.
577
+ if (quiet && line.type === "message_end") {
578
+ const { text: _text, ...rest } = line;
579
+ io.line(rest);
580
+ } else {
581
+ io.line(line);
582
+ }
583
+ }
537
584
  break;
538
585
  }
539
586
  case "auto_retry_start": {
@@ -604,27 +651,81 @@ export async function runWorker(
604
651
  }
605
652
  });
606
653
 
607
- const result = (name: "done" | "cancelled"): WorkerResult => ({
608
- type: "result",
609
- result: name,
610
- sessionId: session.sessionFile ?? null,
611
- usage: tally.usage,
612
- cost: tally.cost,
613
- finalMessage: session.getLastAssistantText() ?? null,
614
- ...(tally.lastUsage === undefined
615
- ? {}
616
- : {
617
- context: {
618
- used:
619
- tally.lastUsage.input +
620
- tally.lastUsage.cache_read +
621
- tally.lastUsage.cache_write,
622
- ...(model?.contextWindow !== undefined && model.contextWindow > 0
623
- ? { window: model.contextWindow }
624
- : {}),
625
- },
626
- }),
627
- });
654
+ // What the reply said and the context it ended with, held back from the
655
+ // flush turn and the compaction that may follow it.
656
+ let heldFinal: string | null | undefined;
657
+ let heldUsed: number | undefined;
658
+ let compaction: WorkerCompaction | undefined;
659
+ const usedNow = (): number | undefined =>
660
+ tally.lastUsage === undefined
661
+ ? undefined
662
+ : tally.lastUsage.input + tally.lastUsage.cache_read + tally.lastUsage.cache_write;
663
+
664
+ const result = (name: "done" | "cancelled"): WorkerResult => {
665
+ const used = heldUsed ?? usedNow();
666
+ return {
667
+ type: "result",
668
+ result: name,
669
+ sessionId: session.sessionFile ?? null,
670
+ usage: tally.usage,
671
+ cost: tally.cost,
672
+ finalMessage: heldFinal !== undefined ? heldFinal : (session.getLastAssistantText() ?? null),
673
+ ...(compaction === undefined ? {} : { compaction }),
674
+ ...(used === undefined
675
+ ? {}
676
+ : {
677
+ context: {
678
+ used,
679
+ ...(model?.contextWindow !== undefined && model.contextWindow > 0
680
+ ? { window: model.contextWindow }
681
+ : {}),
682
+ },
683
+ }),
684
+ };
685
+ };
686
+
687
+ // After a turn (ADR 0023 D12): when the context is over the share of the
688
+ // window the input names, or the input asks for it, one silent turn lets the
689
+ // agent write what it should keep, then pi compacts the session. A failed
690
+ // flush or compaction never fails the reply.
691
+ const compactIfDue = async (options: WorkerCompact): Promise<void> => {
692
+ const usage = session.getContextUsage();
693
+ const window = usage?.contextWindow ?? model?.contextWindow ?? 0;
694
+ const before = usage?.tokens ?? usedNow() ?? 0;
695
+ const forced = options.only === true || options.now === true;
696
+ if (!forced && !(window > 0 && before >= options.at * window)) return;
697
+ heldFinal = options.only === true ? null : (session.getLastAssistantText() ?? null);
698
+ heldUsed = usedNow();
699
+ let flushed = false;
700
+ if (options.flush !== undefined) {
701
+ const errorBefore = tally.lastError;
702
+ quiet = true;
703
+ settled = arm();
704
+ try {
705
+ await session.prompt(options.flush, { expandPromptTemplates: false });
706
+ if (!cancelled) await settled;
707
+ flushed = tally.lastError === undefined;
708
+ } catch (error) {
709
+ io.log(`the memory flush before compaction failed: ${messageOf(error)}`);
710
+ } finally {
711
+ quiet = false;
712
+ tally.lastError = errorBefore;
713
+ }
714
+ }
715
+ if (cancelled) return;
716
+ try {
717
+ const done = await session.compact();
718
+ compaction = {
719
+ reason: forced ? "manual" : "threshold",
720
+ before: done.tokensBefore,
721
+ ...(done.estimatedTokensAfter === undefined ? {} : { after: done.estimatedTokensAfter }),
722
+ flushed,
723
+ };
724
+ if (done.estimatedTokensAfter !== undefined) heldUsed = done.estimatedTokensAfter;
725
+ } catch (error) {
726
+ io.log(`the compaction failed: ${messageOf(error)}`);
727
+ }
728
+ };
628
729
 
629
730
  // Every way this run ends writes its Result here: text still held back as a
630
731
  // possible secret prefix is released first.
@@ -646,6 +747,7 @@ export async function runWorker(
646
747
  let cancelled = cancel.aborted;
647
748
  const onCancel = (): void => {
648
749
  cancelled = true;
750
+ session.abortCompaction();
649
751
  void session.abort();
650
752
  };
651
753
  cancel.addEventListener("abort", onCancel, { once: true });
@@ -658,7 +760,7 @@ export async function runWorker(
658
760
  });
659
761
 
660
762
  try {
661
- if (!cancelled) {
763
+ if (!cancelled && input.compact?.only !== true) {
662
764
  try {
663
765
  const images = await Promise.all((input.images ?? []).map((image) => readImage(image)));
664
766
  // The prompt is operad's text, not a line at pi's terminal: a leading
@@ -684,6 +786,9 @@ export async function runWorker(
684
786
  }
685
787
  if (!cancelled) await settled;
686
788
  }
789
+ if (!cancelled && input.compact !== undefined && tally.lastError === undefined) {
790
+ await compactIfDue(input.compact);
791
+ }
687
792
  if (cancelled) {
688
793
  await session.abort();
689
794
  return finish(result("cancelled"), EXIT_CANCELLED);