@felan-ai/ext-session-compaction 0.7.1 → 0.9.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/NOTICE CHANGED
@@ -1,6 +1,7 @@
1
1
  @felan-ai/ext-session-compaction
2
2
 
3
- This package is original Felan MIT-licensed code. Its design was informed by
3
+ This package includes original Felan MIT-licensed code and the adapted portions
4
+ identified below. Its design was informed by
4
5
  the MIT-licensed pi-smart-compact 9.6.2 review at
5
6
  https://github.com/alpertarhan/pi-smart-compact/tree/687f72c45d27f98ca36d7d1ca9b3941817b0e223
6
7
  and the active-lineage recall design in @sting8k/pi-vcc 0.7.2, reviewed at
@@ -17,3 +18,32 @@ No source code from either package is copied into this package.
17
18
  This package uses TypeBox 1.1.38 from
18
19
  https://github.com/sinclairzx81/typebox, licensed under the MIT License.
19
20
  Copyright (c) 2017-2026 Haydn Paterson.
21
+
22
+ Portions of src/internal/cache-state.ts and src/expiry.ts are adapted from the npm package
23
+ pi-cached-compaction 0.1.0:
24
+ https://www.npmjs.com/package/pi-cached-compaction/v/0.1.0
25
+ https://github.com/nicobailon/pi-cached-compaction
26
+ Copyright (c) Nico Bailon.
27
+ Licensed under the MIT License:
28
+
29
+ MIT License
30
+
31
+ Copyright (c) Nico Bailon
32
+
33
+ Permission is hereby granted, free of charge, to any person obtaining a copy
34
+ of this software and associated documentation files (the "Software"), to deal
35
+ in the Software without restriction, including without limitation the rights
36
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
37
+ copies of the Software, and to permit persons to whom the Software is
38
+ furnished to do so, subject to the following conditions:
39
+
40
+ The above copyright notice and this permission notice shall be included in all
41
+ copies or substantial portions of the Software.
42
+
43
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
44
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
45
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
46
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
47
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
48
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
49
+ SOFTWARE.
package/README.md CHANGED
@@ -3,10 +3,9 @@
3
3
  Portable, bounded verified session compaction and active-lineage recall for
4
4
  Felan hosts.
5
5
 
6
- When enabled, the extension uses classifier compaction by default through Pi's
7
- `session_before_compact` hook when the runtime exposes a classifier. Without
8
- that optional capability it uses the verified summary method, which inherits
9
- the active session model by default. Evidence is priority-packed within bounded
6
+ When enabled, the extension uses the verified summary method by default through
7
+ Pi's `session_before_compact` hook. It inherits the active session model unless a
8
+ summary-model tier is configured. Evidence is priority-packed within bounded
10
9
  lanes. A split-turn lane preserves the actual user input, assistant text and
11
10
  reasoning, and normalized tool outcomes in chronological order. Successful file
12
11
  reads retain their path rather than file contents; writes and patches retain
@@ -16,24 +15,29 @@ decisions/state take precedence over repetitive successful tool output.
16
15
  The `sessionCompaction.model` setting may instead select `xhigh`, `high`,
17
16
  `medium`, or `low`; tiers use the host's allowed models and prefer the active
18
17
  provider/family. An unavailable tier falls back to inherit.
19
- `sessionCompaction.method` defaults to `classifier`, which selectively retains
20
- the prepared transcript when the optional runtime classifier is available and
21
- otherwise uses the verified summary method. Set it to `summary` to disable
22
- classification explicitly. Classifier compaction does not make a summary-model
23
- request, but it does send bounded compaction evidence to the host-injected
24
- classifier's provider. All eligible bulky
18
+ `sessionCompaction.method` defaults to `summary`. Set it to `classifier` to opt
19
+ into fast selective retention of the prepared transcript when the optional
20
+ runtime classifier is available; otherwise it uses the verified summary method.
21
+ Successful classifier compaction does not make a summary-model request, but it
22
+ does send bounded compaction evidence to the
23
+ host-injected classifier's provider. All eligible bulky
25
24
  `observation`, `command`, and `test` results admitted by the central evidence
26
25
  bounds are classified (keep exact contents, keep outcome only, or drop as
27
26
  obsolete). Agent Core may partition the questions across provider requests.
28
- Commands and tests may be shortened but not dropped. Classifier failure returns
29
- control to native Pi. Classifier traces go to `pi.runtime.logger`; they are not
30
- written to session JSONL.
27
+ Commands and tests may be shortened but not dropped. Classifier failure enters
28
+ the verified summary request below using the configured `sessionCompaction.model`.
29
+ For ordinary compaction, native Pi takes over if that chain fails or classifier
30
+ split-prefix preparation fails; the latter shares rendering and bounds with the
31
+ summary prompt. Classifier traces go to
32
+ `pi.runtime.logger`; they are not written to session JSONL.
31
33
  Pi remains the owner of compaction preparation,
32
34
  cut points, retained tails, session trees, overflow recovery, and persistence.
33
- If the extension is absent or a recoverable generation/validation failure occurs
34
- before acceptance, Pi's native summarizer remains in control. A failure after Pi
35
- accepts a custom result cannot automatically rerun native compaction.
36
- Every recoverable fallback emits a warning that Pi native compaction will take
35
+ For ordinary compaction, if the extension is absent or a recoverable
36
+ generation/validation failure occurs before acceptance, Pi's native summarizer
37
+ remains in control. Cache-expiry compaction instead cancels if the configured
38
+ method and its verified summary fallback fail. A failure after Pi accepts a
39
+ custom result cannot automatically rerun native compaction.
40
+ Every native fallback emits a warning that Pi native compaction will take
37
41
  over and persists one bounded metadata-only `custom` entry with the fallback
38
42
  reason and sanitized model error details. The entry is not rendered, sent to
39
43
  the model, or returned by `session_recall`; it records delegation, not native
@@ -47,15 +51,15 @@ details for troubleshooting.
47
51
  The split-turn narrative is mandatory, while lower-priority tool records may be
48
52
  omitted by the central extraction bounds. Compaction reads Pi's prepared
49
53
  messages through Agent Core's shared lossless text-block reader, then
50
- then applies its own status extraction, evidence ranking, deduplication and
54
+ applies its own status extraction, evidence ranking, deduplication and
51
55
  bounded selection. Its compacted evidence is not a lossless transcript and
52
56
  must not replace the original source used for cross-session memory. Summary
53
57
  output uses Pi's prepared reserve-token budget and the selected model's limits;
54
58
  prompt fit uses the model
55
59
  context window. Classifier output is not rejected merely for exceeding an
56
- extension-defined byte size. If required evidence or a model request cannot fit
57
- safely, the extension returns no custom result before acceptance and native Pi
58
- compaction takes over. The prompt still asks for canonical checkpoint headings,
60
+ extension-defined byte size. For ordinary compaction, if required evidence or a
61
+ model request cannot fit safely, the extension returns no custom result before
62
+ acceptance and native Pi compaction takes over. The prompt still asks for canonical checkpoint headings,
59
63
  but a non-empty summary is accepted even if those headings are missing.
60
64
  Unsupported completion or verification claims are still rejected. These
61
65
  safeguards do not prove semantic completeness.
@@ -82,22 +86,71 @@ The local configuration is:
82
86
  ```json
83
87
  {
84
88
  "extensionConfig": {
85
- "sessionCompaction": { "method": "classifier", "model": "inherit" }
89
+ "sessionCompaction": {
90
+ "method": "summary",
91
+ "model": "inherit",
92
+ "compactBeforeCacheExpiry": true,
93
+ "minContextTokens": 200000
94
+ }
86
95
  }
87
96
  }
88
97
  ```
89
98
 
90
99
  The equivalent CLI override is
91
100
  `--session-compaction-model <inherit|xhigh|high|medium|low>`. The setting is
92
- resolved when a new runtime is constructed. A selected-model request still
93
- makes only one attempt; generation or validation failure returns control to
94
- native Pi, which uses the active model. Summary requests set
95
- `cacheRetention: none` and are separate from the main agent request.
101
+ resolved when a new runtime is constructed.
102
+
103
+ ## Summary requests
104
+
105
+ The summary method, including fallback after classifier failure, makes one
106
+ fresh verified request using a separate summary prompt and `cacheRetention: none`.
107
+ It uses the same provider idle timeout as agent requests. If the request or its
108
+ validation fails before acceptance, ordinary compaction falls back to native Pi.
109
+ Cancellation stops the chain. Expiry-triggered compaction cancels on failure
110
+ instead of invoking native Pi.
111
+
112
+ Accepted summary and classifier results append Pi-format `<read-files>` and
113
+ `<modified-files>` sections and store the lists in their details. Lists merge the
114
+ latest compaction's file details, including previous Felan compactions, with Pi's
115
+ prepared file operations; they are sorted, deduplicated, and bounded to 200 paths
116
+ per list and 1,024 bytes per path. Modified paths are omitted from the read-only
117
+ list.
118
+
119
+ The logger emits an info-level `session compaction request` record for every
120
+ summary request, including failed ones. It records the trigger, model, outcome,
121
+ latency, and, when available, input/cache-read/cache-write/output tokens and cost.
122
+ `cacheShare` is cache-read tokens divided by total input tokens, rounded to three
123
+ decimals; it is omitted for zero total input. Classifier traces remain separate
124
+ debug logs. Request logs and fallback diagnostics never enter model context.
125
+
126
+ ## Before cache expiry
127
+
128
+ `compactBeforeCacheExpiry` defaults to `true`. At agent turn end, and on session
129
+ start, tree navigation, or model changes, the extension schedules a countdown to
130
+ about 20 seconds before a **known** cache lifetime expires. When it fires, it
131
+ rechecks expiry, idle state, queued messages, and context usage. Pi cache-warming
132
+ events extend the expiry and cause the countdown to be rescheduled.
133
+
134
+ Compaction runs only when Pi auto-compaction is not disabled
135
+ (`pi.getSettings().compaction.enabled !== false`), the agent is still idle with
136
+ nothing queued, and context usage is at least `minContextTokens` (default 200000;
137
+ a nonnegative integer). It uses the configured compaction method: classifier
138
+ when selected and available, with a fresh verified summary as fallback; otherwise
139
+ the fresh verified summary directly. A summary model must resolve unless the
140
+ selected classifier is available. Every pre-acceptance failure that exhausts
141
+ these paths cancels the attempt without a native fallback diagnostic or warning.
142
+ Expiry-triggered attempts **never** invoke native Pi. Accepted results record
143
+ `trigger: 'cache-expiry'`, and summary request logs use the same trigger. The user
144
+ receives a notification before compaction.
145
+
146
+ Unknown lifetimes, including `openai-codex` models in Pi's catalog, never trigger
147
+ expiry compaction. Set `compactBeforeCacheExpiry: false` to disable idle compaction
148
+ without changing ordinary compaction.
96
149
 
97
150
  ## Development
98
151
 
99
152
  ```sh
100
153
  pnpm --filter @felan-ai/ext-session-compaction build
101
154
  pnpm --filter @felan-ai/ext-session-compaction type-check
102
- pnpm --filter @felan-ai/ext-session-compaction test
155
+ scripts/test-isolated.sh pnpm --filter @felan-ai/ext-session-compaction test
103
156
  ```
@@ -1,6 +1,6 @@
1
1
  import { type AssistantMessage, type Context, type ExtensionContext, type FelanExtension, type Model } from '@felan-ai/agent-core';
2
2
  import { type SessionCompactionDetailsV1 } from './internal/contracts.js';
3
- import type { SessionCompactionMethod, SessionCompactionModel } from './config.js';
3
+ import { type SessionCompactionMethod, type SessionCompactionModel } from './config.js';
4
4
  import { type EvidencePruneReport } from './prune.js';
5
5
  export interface SessionCompactionDetails extends SessionCompactionDetailsV1 {
6
6
  readonly attemptId: string;
@@ -12,6 +12,9 @@ export interface SessionCompactionDetails extends SessionCompactionDetailsV1 {
12
12
  readonly modelFallback?: 'inherit';
13
13
  readonly method?: SessionCompactionMethod;
14
14
  readonly prune?: EvidencePruneReport;
15
+ readonly readFiles?: readonly string[];
16
+ readonly modifiedFiles?: readonly string[];
17
+ readonly trigger?: 'cache-expiry';
15
18
  }
16
19
  export interface CompactionExtensionOptions {
17
20
  readonly complete?: (model: Model<any>, context: Context, options: Record<string, unknown>, ctx: ExtensionContext) => Promise<AssistantMessage>;
@@ -1 +1 @@
1
- {"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../src/compaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,gBAAgB,EACrB,KAAK,OAAO,EACZ,KAAK,gBAAgB,EACrB,KAAK,cAAc,EAEnB,KAAK,KAAK,EACX,MAAM,sBAAsB,CAAC;AAM9B,OAAO,EAGL,KAAK,0BAA0B,EAChC,MAAM,yBAAyB,CAAC;AAGjC,OAAO,KAAK,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AACnF,OAAO,EAA0C,KAAK,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAqB9F,MAAM,WAAW,wBAAyB,SAAQ,0BAA0B;IAC1E,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,QAAQ,CAAC,cAAc,EAAE,sBAAsB,CAAC;IAChD,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,CAAC;IACnC,QAAQ,CAAC,MAAM,CAAC,EAAE,uBAAuB,CAAC;IAC1C,QAAQ,CAAC,KAAK,CAAC,EAAE,mBAAmB,CAAC;CACtC;AAED,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAClB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,GAAG,EAAE,gBAAgB,KAClB,OAAO,CAAC,gBAAgB,CAAC,CAAC;CAChC;AAED,wBAAgB,gCAAgC,CAC9C,OAAO,GAAE,0BAA+B,GACvC,cAAc,CA+LhB;AAgND,eAAO,MAAM,yBAAyB,iDAA4B,CAAC"}
1
+ {"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../src/compaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,gBAAgB,EACrB,KAAK,OAAO,EACZ,KAAK,gBAAgB,EACrB,KAAK,cAAc,EAEnB,KAAK,KAAK,EACX,MAAM,sBAAsB,CAAC;AAM9B,OAAO,EAGL,KAAK,0BAA0B,EAChC,MAAM,yBAAyB,CAAC;AAGjC,OAAO,EAAqC,KAAK,uBAAuB,EAAE,KAAK,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAG3H,OAAO,EAA0C,KAAK,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAqB9F,MAAM,WAAW,wBAAyB,SAAQ,0BAA0B;IAC1E,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,QAAQ,CAAC,cAAc,EAAE,sBAAsB,CAAC;IAChD,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,CAAC;IACnC,QAAQ,CAAC,MAAM,CAAC,EAAE,uBAAuB,CAAC;IAC1C,QAAQ,CAAC,KAAK,CAAC,EAAE,mBAAmB,CAAC;IACrC,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C,QAAQ,CAAC,OAAO,CAAC,EAAE,cAAc,CAAC;CACnC;AAED,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAClB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,GAAG,EAAE,gBAAgB,KAClB,OAAO,CAAC,gBAAgB,CAAC,CAAC;CAChC;AAED,wBAAgB,gCAAgC,CAC9C,OAAO,GAAE,0BAA+B,GACvC,cAAc,CAmPhB;AA+RD,eAAO,MAAM,yBAAyB,iDAA4B,CAAC"}
@@ -5,7 +5,10 @@ import { extractEvidence } from './internal/evidence.js';
5
5
  import { prepareEvidenceSpan } from './internal/prepared-span.js';
6
6
  import { renderSplitTurnPrefix } from './internal/split-prefix.js';
7
7
  import { FALLBACK_DIAGNOSTIC_CUSTOM_TYPE, } from './internal/contracts.js';
8
- import { createFallbackDiagnostic, fallbackDiagnosticText } from './internal/fallback-diagnostic.js';
8
+ import { createFallbackDiagnostic, fallbackDiagnosticText, sanitizeErrorMessage } from './internal/fallback-diagnostic.js';
9
+ import { DEFAULT_SESSION_COMPACTION_CONFIG } from './config.js';
10
+ import { registerCacheExpiryCompaction } from './expiry.js';
11
+ import { collectFileLists, formatFileLists, latestCompactionDetails, stripFileLists } from './internal/file-lists.js';
9
12
  import { pruneEvidence } from './prune.js';
10
13
  const SYSTEM_PROMPT = [
11
14
  'You are a session checkpoint summarizer.',
@@ -20,6 +23,16 @@ export function createSessionCompactionExtension(options = {}) {
20
23
  return (pi) => {
21
24
  let pending;
22
25
  let prune = { status: 'off' };
26
+ const expiry = registerCacheExpiryCompaction(pi, {
27
+ enabled: configuredBoolean(pi.config?.compactBeforeCacheExpiry),
28
+ minContextTokens: configuredMinContextTokens(pi.config?.minContextTokens),
29
+ canCompact(ctx) {
30
+ if (configuredMethod(pi.config?.method) === 'classifier' && pi.runtime.classifier)
31
+ return { ok: true };
32
+ return resolveModel(ctx, configuredModel(pi.config?.model))
33
+ ? { ok: true } : { ok: false, reason: 'model-unavailable' };
34
+ },
35
+ });
23
36
  const clear = () => { pending = undefined; };
24
37
  const fallback = (event, ctx, reason, details = {}, selectedModel) => {
25
38
  if (event.signal.aborted)
@@ -49,29 +62,22 @@ export function createSessionCompactionExtension(options = {}) {
49
62
  clear();
50
63
  const classifier = pi.runtime.classifier;
51
64
  prune = { status: 'off' };
65
+ const fromExpiry = expiry.takeTrigger();
52
66
  if (event.signal.aborted)
53
67
  return { cancel: true };
54
- if (configuredMethod(pi.config?.method) === 'classifier' && classifier) {
55
- const span = prepareEvidenceSpan({ preparation: event.preparation, branchEntries: event.branchEntries });
56
- try {
57
- const pruned = await pruneEvidence(extractEvidence(span), span, classifier, {
58
- trigger: event.reason,
59
- ...(event.customInstructions === undefined ? {} : { customInstructions: event.customInstructions }),
60
- ...(event.preparation.previousSummary === undefined ? {} : { previousSummary: event.preparation.previousSummary }),
61
- signal: event.signal,
62
- });
63
- if (event.signal.aborted)
64
- return { cancel: true };
65
- prune = pruned.report;
66
- logPrune(pi, ctx.sessionManager.getSessionId(), pruned.debug);
67
- if (pruned.report.status === 'skipped' && pruned.report.reason === 'classifier-failed') {
68
- return fallback(event, ctx, 'model-request-failed');
69
- }
70
- const summary = buildClassifierSummary(event, span, pruned.evidence);
71
- if (summary === undefined) {
72
- return fallback(event, ctx, 'prompt-preparation-failed');
73
- }
74
- const attemptId = uuidv7();
68
+ const decline = (...args) => {
69
+ if (!fromExpiry)
70
+ return fallback(...args);
71
+ logExpiryCancel(pi, ctx.sessionManager.getSessionId(), args[2], args[3]?.errorMessage);
72
+ return { cancel: true };
73
+ };
74
+ try {
75
+ const fileLists = collectFileLists(event.preparation.fileOps, latestCompactionDetails(event.branchEntries));
76
+ const fileDetails = {
77
+ ...(fileLists.readFiles.length > 0 ? { readFiles: fileLists.readFiles } : {}),
78
+ ...(fileLists.modifiedFiles.length > 0 ? { modifiedFiles: fileLists.modifiedFiles } : {}),
79
+ };
80
+ const accept = (summary, continuity, selection, usage, attemptId = uuidv7()) => {
75
81
  pending = {
76
82
  id: attemptId,
77
83
  sessionId: ctx.sessionManager.getSessionId(),
@@ -81,114 +87,154 @@ export function createSessionCompactionExtension(options = {}) {
81
87
  summary,
82
88
  };
83
89
  const details = {
84
- ...createCompactionDetails(mergeContinuity(undefined, pruned.evidence)),
90
+ ...createCompactionDetails(continuity),
85
91
  attemptId,
86
92
  sessionId: pending.sessionId,
87
93
  reason: event.reason,
88
94
  willRetry: event.willRetry,
89
- requestedModel: 'inherit',
90
- selectedModel: classifierModel(pruned.report),
91
- method: 'classifier',
95
+ ...selection,
92
96
  prune,
97
+ ...fileDetails,
98
+ ...(fromExpiry ? { trigger: 'cache-expiry' } : {}),
93
99
  };
94
100
  return { compaction: {
95
101
  summary,
96
102
  firstKeptEntryId: event.preparation.firstKeptEntryId,
97
103
  tokensBefore: event.preparation.tokensBefore,
104
+ ...(usage === undefined ? {} : { usage }),
98
105
  details,
99
106
  } };
107
+ };
108
+ if (configuredMethod(pi.config?.method) === 'classifier' && classifier) {
109
+ const span = prepareEvidenceSpan({ preparation: event.preparation, branchEntries: event.branchEntries });
110
+ const evidence = extractEvidence(span);
111
+ let pruned;
112
+ try {
113
+ pruned = await pruneEvidence(evidence, span, classifier, {
114
+ trigger: event.reason,
115
+ ...(event.customInstructions === undefined ? {} : { customInstructions: event.customInstructions }),
116
+ ...(event.preparation.previousSummary === undefined ? {} : { previousSummary: event.preparation.previousSummary }),
117
+ signal: event.signal,
118
+ });
119
+ }
120
+ catch (error) {
121
+ if (event.signal.aborted)
122
+ return { cancel: true };
123
+ prune = { status: 'skipped', reason: 'classifier-failed' };
124
+ logClassifierFailure(pi, ctx.sessionManager.getSessionId(), error);
125
+ }
126
+ if (event.signal.aborted)
127
+ return { cancel: true };
128
+ if (pruned) {
129
+ prune = pruned.report;
130
+ logPrune(pi, ctx.sessionManager.getSessionId(), pruned.debug);
131
+ if (pruned.report.status === 'skipped' && pruned.report.reason === 'classifier-failed') {
132
+ logClassifierFailure(pi, ctx.sessionManager.getSessionId(), pruned.debug.error);
133
+ }
134
+ else {
135
+ const transcript = buildClassifierSummary(event, span, pruned.evidence);
136
+ if (transcript === undefined) {
137
+ return decline(event, ctx, 'prompt-preparation-failed');
138
+ }
139
+ const summary = stripFileLists(transcript) + formatFileLists(fileLists);
140
+ return accept(summary, mergeContinuity(undefined, pruned.evidence), {
141
+ requestedModel: 'inherit',
142
+ selectedModel: classifierModel(pruned.report),
143
+ method: 'classifier',
144
+ });
145
+ }
146
+ }
147
+ }
148
+ const modelSelection = resolveModel(ctx, configuredModel(pi.config?.model));
149
+ if (!modelSelection)
150
+ return decline(event, ctx, 'model-unavailable');
151
+ const span = prepareEvidenceSpan({
152
+ preparation: event.preparation,
153
+ branchEntries: event.branchEntries,
154
+ });
155
+ const evidence = extractEvidence(span);
156
+ const prior = latestContinuity(event.branchEntries);
157
+ const continuity = mergeContinuity(prior, evidence);
158
+ const timeoutMs = summaryTimeoutMs(pi);
159
+ const prompt = buildPrompt(event, span, evidence, prior ? renderContinuity(prior, DEFAULT_EXTRACTION_BOUNDS.maxContinuityBytes) : '', modelSelection.model, event.preparation);
160
+ if (prompt === undefined)
161
+ return decline(event, ctx, 'prompt-budget-exceeded', {}, modelSelection.model);
162
+ const attemptId = uuidv7();
163
+ const signal = event.signal;
164
+ const started = Date.now();
165
+ let response;
166
+ try {
167
+ const requestOptions = completionOptions(ctx, modelSelection.model, attemptId, signal, summaryOutputTokens(event.preparation, modelSelection.model), timeoutMs);
168
+ response = options.complete
169
+ ? await options.complete(modelSelection.model, summaryContext(prompt), requestOptions, ctx)
170
+ : await ctx.modelRegistry.complete(modelSelection.model, summaryContext(prompt), requestOptions);
100
171
  }
101
172
  catch (error) {
173
+ logSummaryRequest(pi, {
174
+ sessionId: ctx.sessionManager.getSessionId(), trigger: fromExpiry ? 'cache-expiry' : event.reason,
175
+ model: modelReference(modelSelection.model), latencyMs: Date.now() - started,
176
+ outcome: 'failed', reason: event.signal.aborted ? 'aborted' : boundedReason(sanitizeErrorMessage(error)),
177
+ });
102
178
  if (event.signal.aborted)
103
179
  return { cancel: true };
104
- prune = { status: 'skipped', reason: 'classifier-failed' };
105
- return fallback(event, ctx, 'model-request-failed', { errorMessage: error });
180
+ return decline(event, ctx, signal.aborted ? 'model-timeout' : 'model-request-failed', {
181
+ errorMessage: error,
182
+ }, modelSelection.model);
106
183
  }
107
- }
108
- const modelSelection = resolveModel(ctx, configuredModel(pi.config?.model));
109
- if (!modelSelection)
110
- return fallback(event, ctx, 'model-unavailable');
111
- const span = prepareEvidenceSpan({
112
- preparation: event.preparation,
113
- branchEntries: event.branchEntries,
114
- });
115
- let evidence = extractEvidence(span);
116
- const prior = latestContinuity(event.branchEntries);
117
- const continuity = mergeContinuity(prior, evidence);
118
- const prompt = buildPrompt(event, span, evidence, prior ? renderContinuity(prior, DEFAULT_EXTRACTION_BOUNDS.maxContinuityBytes) : '', modelSelection.model, event.preparation);
119
- if (prompt === undefined)
120
- return fallback(event, ctx, 'prompt-budget-exceeded', {}, modelSelection.model);
121
- const attemptId = uuidv7();
122
- const signal = event.signal;
123
- let response;
124
- try {
125
- response = options.complete
126
- ? await options.complete(modelSelection.model, summaryContext(prompt), completionOptions(ctx, modelSelection.model, attemptId, signal, summaryOutputTokens(event.preparation, modelSelection.model)), ctx)
127
- : await ctx.modelRegistry.complete(modelSelection.model, summaryContext(prompt), completionOptions(ctx, modelSelection.model, attemptId, signal, summaryOutputTokens(event.preparation, modelSelection.model)));
184
+ const latencyMs = Date.now() - started;
185
+ const logResponse = (outcome, reason) => {
186
+ logSummaryRequest(pi, {
187
+ sessionId: ctx.sessionManager.getSessionId(), trigger: fromExpiry ? 'cache-expiry' : event.reason,
188
+ model: modelReference(modelSelection.model), latencyMs,
189
+ outcome, usage: response.usage, ...(reason === undefined ? {} : { reason }),
190
+ });
191
+ };
192
+ if (event.signal.aborted) {
193
+ logResponse('failed', 'aborted');
194
+ return { cancel: true };
195
+ }
196
+ if (response.stopReason !== 'stop') {
197
+ logResponse(response.stopReason === 'error' || response.stopReason === 'aborted' ? 'failed' : 'rejected', `response-${response.stopReason}`);
198
+ return decline(event, ctx, 'model-response-invalid', {
199
+ errorMessage: response.errorMessage,
200
+ stopReason: response.stopReason,
201
+ }, modelSelection.model);
202
+ }
203
+ if (response.content.some((part) => part.type === 'toolCall')) {
204
+ logResponse('rejected', 'response-tool-call');
205
+ return decline(event, ctx, 'model-response-invalid', {
206
+ stopReason: 'toolUse', detail: 'model returned a tool call',
207
+ }, modelSelection.model);
208
+ }
209
+ const rawSummary = response.content
210
+ .filter((part) => part.type === 'text')
211
+ .map((part) => part.text)
212
+ .join('\n')
213
+ .trim();
214
+ if (!rawSummary) {
215
+ logResponse('rejected', 'response-empty');
216
+ return decline(event, ctx, 'model-response-invalid', { detail: 'empty summary' }, modelSelection.model);
217
+ }
218
+ if (hasUnsupportedClaims(rawSummary, evidence)) {
219
+ logResponse('rejected', 'unsupported-claim');
220
+ return decline(event, ctx, 'model-response-unsupported', { detail: 'unsupported completion claim' }, modelSelection.model);
221
+ }
222
+ const summary = appendContinuity(stripFileLists(rawSummary), continuity) + formatFileLists(fileLists);
223
+ const accepted = accept(summary, continuity, {
224
+ requestedModel: modelSelection.requested,
225
+ selectedModel: modelReference(modelSelection.model),
226
+ ...(modelSelection.fallback === undefined ? {} : { modelFallback: modelSelection.fallback }),
227
+ method: 'summary',
228
+ }, response.usage, attemptId);
229
+ logResponse('accepted');
230
+ return accepted;
128
231
  }
129
232
  catch (error) {
130
- if (event.signal.aborted)
131
- return { cancel: true };
132
- return fallback(event, ctx, signal.aborted ? 'model-timeout' : 'model-request-failed', {
133
- errorMessage: error,
134
- }, modelSelection.model);
233
+ if (!fromExpiry)
234
+ throw error;
235
+ clear();
236
+ return decline(event, ctx, 'prompt-preparation-failed', { errorMessage: error });
135
237
  }
136
- if (event.signal.aborted)
137
- return { cancel: true };
138
- if (signal.aborted)
139
- return fallback(event, ctx, 'model-timeout', {}, modelSelection.model);
140
- if (response.stopReason !== 'stop')
141
- return fallback(event, ctx, 'model-response-invalid', {
142
- errorMessage: response.errorMessage,
143
- stopReason: response.stopReason,
144
- }, modelSelection.model);
145
- if (response.content.some((part) => part.type === 'toolCall'))
146
- return fallback(event, ctx, 'model-response-invalid', {
147
- stopReason: 'toolUse', detail: 'model returned a tool call',
148
- }, modelSelection.model);
149
- const rawSummary = response.content
150
- .filter((part) => part.type === 'text')
151
- .map((part) => part.text)
152
- .join('\n')
153
- .trim();
154
- if (!rawSummary)
155
- return fallback(event, ctx, 'model-response-invalid', {
156
- detail: 'empty summary',
157
- }, modelSelection.model);
158
- if (hasUnsupportedClaims(rawSummary, evidence))
159
- return fallback(event, ctx, 'model-response-unsupported', {
160
- detail: 'unsupported completion claim',
161
- }, modelSelection.model);
162
- const summary = appendContinuity(rawSummary, continuity);
163
- pending = {
164
- id: attemptId,
165
- sessionId: ctx.sessionManager.getSessionId(),
166
- firstKeptEntryId: event.preparation.firstKeptEntryId,
167
- reason: event.reason,
168
- willRetry: event.willRetry,
169
- summary,
170
- };
171
- const details = {
172
- ...createCompactionDetails(continuity),
173
- attemptId,
174
- sessionId: pending.sessionId,
175
- reason: event.reason,
176
- willRetry: event.willRetry,
177
- requestedModel: modelSelection.requested,
178
- selectedModel: modelReference(modelSelection.model),
179
- ...(modelSelection.fallback === undefined ? {} : { modelFallback: modelSelection.fallback }),
180
- method: 'summary',
181
- prune,
182
- };
183
- return {
184
- compaction: {
185
- summary,
186
- firstKeptEntryId: event.preparation.firstKeptEntryId,
187
- tokensBefore: event.preparation.tokensBefore,
188
- ...(response.usage === undefined ? {} : { usage: response.usage }),
189
- details,
190
- },
191
- };
192
238
  });
193
239
  pi.on('session_compact', (event, ctx) => {
194
240
  if (!pending || !event.fromExtension || !isMatchingPersistedAttempt(event.compactionEntry.details, pending)) {
@@ -276,10 +322,11 @@ function summaryContext(prompt) {
276
322
  messages: [{ role: 'user', content: [{ type: 'text', text: prompt }], timestamp: Date.now() }],
277
323
  };
278
324
  }
279
- function completionOptions(ctx, model, sessionId, signal, maxTokens) {
325
+ function completionOptions(ctx, model, sessionId, signal, maxTokens, timeoutMs) {
280
326
  return {
281
327
  signal,
282
328
  maxTokens,
329
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
283
330
  maxRetries: 0,
284
331
  cacheRetention: 'none',
285
332
  sessionId,
@@ -288,17 +335,34 @@ function completionOptions(ctx, model, sessionId, signal, maxTokens) {
288
335
  : { reasoning: clampThinkingLevel(model, ctx.thinkingLevel) }),
289
336
  };
290
337
  }
338
+ function summaryTimeoutMs(pi) {
339
+ try {
340
+ const settings = pi.getSettings();
341
+ const timeoutMs = settings.retry?.provider?.timeoutMs ?? settings.httpIdleTimeoutMs ?? 300_000;
342
+ return typeof timeoutMs === 'number' && Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : undefined;
343
+ }
344
+ catch {
345
+ return undefined;
346
+ }
347
+ }
291
348
  function configuredModel(value) {
292
349
  return value === 'xhigh' || value === 'high' || value === 'medium' || value === 'low'
293
350
  ? value
294
351
  : 'inherit';
295
352
  }
353
+ function configuredBoolean(value) {
354
+ return typeof value === 'boolean' ? value : true;
355
+ }
356
+ function configuredMinContextTokens(value) {
357
+ return typeof value === 'number' && Number.isInteger(value) && value >= 0
358
+ ? value : DEFAULT_SESSION_COMPACTION_CONFIG.minContextTokens;
359
+ }
296
360
  function summaryOutputTokens(preparation, model) {
297
361
  const reserveTokens = preparation.settings?.reserveTokens ?? 16_384;
298
362
  return Math.min(Math.floor(0.8 * Math.max(1, reserveTokens)), model.maxTokens || Number.POSITIVE_INFINITY);
299
363
  }
300
364
  function configuredMethod(value) {
301
- return value === 'summary' ? 'summary' : 'classifier';
365
+ return value === 'classifier' ? 'classifier' : 'summary';
302
366
  }
303
367
  function classifierModel(report) {
304
368
  return report.status === 'ran' && report.classifier?.provider && report.classifier.model
@@ -376,11 +440,60 @@ function logPrune(pi, sessionId, event) {
376
440
  pi.runtime.logger.child({ component: 'session-compaction' }).debug({
377
441
  sessionId,
378
442
  ...event,
443
+ ...(event.error === undefined ? {} : { error: sanitizeErrorMessage(event.error) }),
379
444
  }, 'session compaction prune');
380
445
  }
381
446
  catch {
382
447
  /* debug must not affect compaction */
383
448
  }
384
449
  }
450
+ function logClassifierFailure(pi, sessionId, error) {
451
+ try {
452
+ const errorMessage = sanitizeErrorMessage(error);
453
+ pi.runtime.logger.child({ component: 'session-compaction' }).warn({
454
+ sessionId,
455
+ ...(errorMessage ? { errorMessage } : {}),
456
+ }, 'session compaction classifier failed; trying verified summary');
457
+ }
458
+ catch {
459
+ /* logging must not affect compaction */
460
+ }
461
+ }
462
+ function logExpiryCancel(pi, sessionId, reason, error) {
463
+ try {
464
+ const errorMessage = sanitizeErrorMessage(error);
465
+ pi.runtime.logger.child({ component: 'session-compaction' }).info({
466
+ sessionId: sanitizeText(sessionId, 256).text,
467
+ trigger: 'cache-expiry',
468
+ reason,
469
+ ...(errorMessage ? { errorMessage } : {}),
470
+ }, 'session compaction cache expiry cancelled');
471
+ }
472
+ catch { }
473
+ }
474
+ function boundedReason(value) {
475
+ return sanitizeText(sanitizeErrorMessage(value), 256).text;
476
+ }
477
+ function logSummaryRequest(pi, request) {
478
+ try {
479
+ const { usage } = request;
480
+ const total = usage ? usage.input + usage.cacheRead + usage.cacheWrite : 0;
481
+ pi.runtime.logger.child({ component: 'session-compaction' }).info({
482
+ sessionId: sanitizeText(request.sessionId, 256).text,
483
+ method: 'summary',
484
+ trigger: request.trigger,
485
+ model: sanitizeText(request.model, 256).text,
486
+ latencyMs: Math.max(0, request.latencyMs),
487
+ outcome: request.outcome,
488
+ ...(request.reason === undefined ? {} : { reason: boundedReason(request.reason) }),
489
+ ...(usage === undefined ? {} : { usage: {
490
+ input: usage.input, cacheRead: usage.cacheRead, cacheWrite: usage.cacheWrite,
491
+ output: usage.output, cost: usage.cost.total,
492
+ } }),
493
+ ...(usage && total > 0 ? { cacheShare: Math.round(usage.cacheRead / total * 1_000) / 1_000 } : {}),
494
+ }, 'session compaction request');
495
+ }
496
+ catch { }
497
+ }
385
498
  export const SESSION_COMPACTION_BOUNDS = DEFAULT_EXTRACTION_BOUNDS;
386
499
  //# sourceMappingURL=compaction.js.map