@bastani/atomic 0.9.20-alpha.2 → 0.9.20-alpha.3
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/CHANGELOG.md +17 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/CHANGELOG.md +6 -0
- package/dist/builtin/web-access/index.bundle.mjs +5 -5
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +78 -31
- package/dist/bun/split-loader.js +13 -0
- package/dist/bun/split-loader.js.map +1 -1
- package/dist/core/agent-session-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-compaction.js +12 -6
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/compaction/compaction-boundary.d.ts +29 -1
- package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
- package/dist/core/compaction/compaction-boundary.js +35 -3
- package/dist/core/compaction/compaction-boundary.js.map +1 -1
- package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/compaction-runner.js +18 -5
- package/dist/core/compaction/compaction-runner.js.map +1 -1
- package/dist/core/compaction/compaction-types.d.ts +7 -0
- package/dist/core/compaction/compaction-types.d.ts.map +1 -1
- package/dist/core/compaction/compaction-types.js.map +1 -1
- package/dist/core/compaction/index.d.ts +1 -0
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/index.js +1 -0
- package/dist/core/compaction/index.js.map +1 -1
- package/dist/core/compaction/whole-context-stats.d.ts +21 -0
- package/dist/core/compaction/whole-context-stats.d.ts.map +1 -0
- package/dist/core/compaction/whole-context-stats.js +32 -0
- package/dist/core/compaction/whole-context-stats.js.map +1 -0
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +11 -1
- package/dist/core/messages.js.map +1 -1
- package/dist/core/model-config.d.ts +85 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +22 -18
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/session-manager-core.d.ts +2 -0
- package/dist/core/session-manager-core.d.ts.map +1 -1
- package/dist/core/session-manager-core.js +26 -3
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/index-extensions.d.ts +1 -1
- package/dist/index-extensions.d.ts.map +1 -1
- package/dist/index-extensions.js.map +1 -1
- package/dist/main-session.d.ts.map +1 -1
- package/dist/main-session.js +5 -6
- package/dist/main-session.js.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.d.ts +2 -0
- package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.js +13 -3
- package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
- package/dist/modes/interactive/interactive-tui.d.ts +3 -6
- package/dist/modes/interactive/interactive-tui.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-tui.js +13 -5
- package/dist/modes/interactive/interactive-tui.js.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +14 -2
- package/dist/utils/clipboard.js.map +1 -1
- package/docs/compaction/reference.md +2 -0
- package/docs/compaction.md +3 -1
- package/docs/getting-started/installation.md +1 -1
- package/docs/keybindings.md +2 -0
- package/docs/models/reference.md +21 -0
- package/docs/workflows/operations.md +5 -1
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
|
@@ -1,8 +1,36 @@
|
|
|
1
1
|
import type { SessionEntry } from "../session-manager-types.ts";
|
|
2
2
|
import { type CompactionSettings } from "./compaction.ts";
|
|
3
3
|
import { type VerbatimCompactionParameters, type VerbatimCompactionPreparation } from "./compaction-types.js";
|
|
4
|
-
/**
|
|
4
|
+
/**
|
|
5
|
+
* Return the independently estimated cost of the protected tail.
|
|
6
|
+
*
|
|
7
|
+
* Only the explicit estimate recorded by `prepareCompactionBoundary` (or a test)
|
|
8
|
+
* is returned. The old fallback of `tokensBefore - region.tokenEstimate` was
|
|
9
|
+
* removed because it mixed the authoritative whole-context count with the
|
|
10
|
+
* heuristic region estimate; when no explicit estimate exists the tail simply
|
|
11
|
+
* contributes nothing rather than a wrong-numbered value. Whether an estimate is
|
|
12
|
+
* registered at all is visible through `hasKeptTailTokenEstimate`, which the
|
|
13
|
+
* fresh rung uses to decide a tail whose size is unknown (P1 #3010).
|
|
14
|
+
*/
|
|
5
15
|
export declare function getKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): number;
|
|
16
|
+
/**
|
|
17
|
+
* Whether an independent tail estimate is registered for this preparation.
|
|
18
|
+
*
|
|
19
|
+
* A preparation built by `prepareCompactionBoundary` always has one. A directly
|
|
20
|
+
* constructed preparation may not; the fresh rung treats a kept tail whose size
|
|
21
|
+
* is unregistered as unknown and drops it conservatively rather than assuming it
|
|
22
|
+
* fits (P1 #3010).
|
|
23
|
+
*/
|
|
24
|
+
export declare function hasKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Record the independent tail estimate for a preparation.
|
|
27
|
+
*
|
|
28
|
+
* `prepareCompactionBoundary` does this itself from the kept-tail messages;
|
|
29
|
+
* this setter is for test preparations built directly and for any other code
|
|
30
|
+
* that constructs a `VerbatimCompactionPreparation` without the boundary
|
|
31
|
+
* preparer. The estimate lives in a module-private map and is never persisted.
|
|
32
|
+
*/
|
|
33
|
+
export declare function setKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation, estimate: number): void;
|
|
6
34
|
export declare function autoDetectCompactionQuery(entries: readonly SessionEntry[]): string;
|
|
7
35
|
/**
|
|
8
36
|
* Planner eligibility, kept separate from boundary preparation.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-boundary.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-boundary.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAmB,YAAY,EAAE,MAAM,6BAA6B,CAAC;AACjF,OAAO,EAAE,KAAK,kBAAkB,EAAyC,MAAM,iBAAiB,CAAC;AAMjG,OAAO,EAIN,KAAK,4BAA4B,EACjC,KAAK,6BAA6B,EAClC,MAAM,uBAAuB,CAAC;AAW/B,
|
|
1
|
+
{"version":3,"file":"compaction-boundary.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-boundary.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAmB,YAAY,EAAE,MAAM,6BAA6B,CAAC;AACjF,OAAO,EAAE,KAAK,kBAAkB,EAAyC,MAAM,iBAAiB,CAAC;AAMjG,OAAO,EAIN,KAAK,4BAA4B,EACjC,KAAK,6BAA6B,EAClC,MAAM,uBAAuB,CAAC;AAW/B;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,6BAA6B,GAAG,MAAM,CAG3F;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,6BAA6B,GAAG,OAAO,CAE5F;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,6BAA6B,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAE3G;AAgDD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CASlF;AAYD;;;;;;;;GAQG;AACH,MAAM,WAAW,yBAAyB;IACzC;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,8FAA8F;AAC9F,wBAAgB,yBAAyB,CACxC,WAAW,EAAE,YAAY,EAAE,EAC3B,QAAQ,EAAE,kBAAkB,EAC5B,OAAO,GAAE,OAAO,CAAC,4BAA4B,CAAM,EACnD,OAAO,GAAE,yBAA8B,GACrC,6BAA6B,GAAG,SAAS,CAuC3C"}
|
|
@@ -6,10 +6,42 @@ import { COMPACTION_AUTO_QUERY, normalizeCompactionParameters, normalizeCompacti
|
|
|
6
6
|
import { MIN_COMPACTABLE_REGION_LINES, VERBATIM_COMPACTION_STRATEGY, } from "./compaction-types.js";
|
|
7
7
|
import { createNumberedRegion, serializeConversationForCompaction } from "./transcript-serialization.js";
|
|
8
8
|
const keptTailTokensByPreparation = new WeakMap();
|
|
9
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* Return the independently estimated cost of the protected tail.
|
|
11
|
+
*
|
|
12
|
+
* Only the explicit estimate recorded by `prepareCompactionBoundary` (or a test)
|
|
13
|
+
* is returned. The old fallback of `tokensBefore - region.tokenEstimate` was
|
|
14
|
+
* removed because it mixed the authoritative whole-context count with the
|
|
15
|
+
* heuristic region estimate; when no explicit estimate exists the tail simply
|
|
16
|
+
* contributes nothing rather than a wrong-numbered value. Whether an estimate is
|
|
17
|
+
* registered at all is visible through `hasKeptTailTokenEstimate`, which the
|
|
18
|
+
* fresh rung uses to decide a tail whose size is unknown (P1 #3010).
|
|
19
|
+
*/
|
|
10
20
|
export function getKeptTailTokenEstimate(preparation) {
|
|
11
|
-
|
|
12
|
-
|
|
21
|
+
const registered = keptTailTokensByPreparation.get(preparation);
|
|
22
|
+
return registered === undefined ? 0 : registered;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Whether an independent tail estimate is registered for this preparation.
|
|
26
|
+
*
|
|
27
|
+
* A preparation built by `prepareCompactionBoundary` always has one. A directly
|
|
28
|
+
* constructed preparation may not; the fresh rung treats a kept tail whose size
|
|
29
|
+
* is unregistered as unknown and drops it conservatively rather than assuming it
|
|
30
|
+
* fits (P1 #3010).
|
|
31
|
+
*/
|
|
32
|
+
export function hasKeptTailTokenEstimate(preparation) {
|
|
33
|
+
return keptTailTokensByPreparation.has(preparation);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Record the independent tail estimate for a preparation.
|
|
37
|
+
*
|
|
38
|
+
* `prepareCompactionBoundary` does this itself from the kept-tail messages;
|
|
39
|
+
* this setter is for test preparations built directly and for any other code
|
|
40
|
+
* that constructs a `VerbatimCompactionPreparation` without the boundary
|
|
41
|
+
* preparer. The estimate lives in a module-private map and is never persisted.
|
|
42
|
+
*/
|
|
43
|
+
export function setKeptTailTokenEstimate(preparation, estimate) {
|
|
44
|
+
keptTailTokensByPreparation.set(preparation, Math.max(0, estimate));
|
|
13
45
|
}
|
|
14
46
|
function messageFromEntry(entry) {
|
|
15
47
|
if (entry.type === "message")
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-boundary.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-boundary.ts"],"names":[],"mappings":"AACA,OAAO,EACN,YAAY,EACZ,0BAA0B,EAC1B,mBAAmB,EACnB,mBAAmB,EACnB,wBAAwB,GACxB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,8BAA8B,EAAE,MAAM,mCAAmC,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEpE,OAAO,EAA2B,qBAAqB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjG,OAAO,EACN,qBAAqB,EACrB,6BAA6B,EAC7B,wBAAwB,GACxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACN,4BAA4B,EAC5B,4BAA4B,GAI5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,oBAAoB,EAAE,kCAAkC,EAAE,MAAM,+BAA+B,CAAC;AAQzG,MAAM,2BAA2B,GAAG,IAAI,OAAO,EAAyC,CAAC;AAEzF,qEAAqE;AACrE,MAAM,UAAU,wBAAwB,CAAC,WAA0C;IAClF,OAAO,CACN,2BAA2B,CAAC,GAAG,CAAC,WAAW,CAAC;QAC5C,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,WAAW,CAAC,YAAY,GAAG,WAAW,CAAC,MAAM,CAAC,aAAa,CAAC,CACxE,CAAC;AACH,CAAC;AAED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EAAE,CAAC,GAAG,GAAG,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CACzE,CAAC;IACF,OAAO,WAAW,CAAC;AACpB,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCustomMessage,\n\tmessageIsLlmVisible,\n\tmessageStartsLlmUserTurn,\n} from \"../messages.ts\";\nimport { normalizeDerivedSessionEntries } from \"../session-entry-normalization.ts\";\nimport { buildSessionContext } from \"../session-manager-history.ts\";\nimport type { CompactionEntry, SessionEntry } from \"../session-manager-types.ts\";\nimport { type CompactionSettings, estimateContextTokens, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCOMPACTION_AUTO_QUERY,\n\tnormalizeCompactionParameters,\n\tnormalizeCompactionQuery,\n} from \"./compaction-parameters.js\";\nimport {\n\tMIN_COMPACTABLE_REGION_LINES,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionParameters,\n\ttype VerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { createNumberedRegion, serializeConversationForCompaction } from \"./transcript-serialization.js\";\n\ninterface VisibleEntry {\n\tentry: SessionEntry;\n\tindex: number;\n\tmessage: AgentMessage;\n}\n\nconst keptTailTokensByPreparation = new WeakMap<VerbatimCompactionPreparation, number>();\n\n/** Return the independently estimated cost of the protected tail. */\nexport function getKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): number {\n\treturn (\n\t\tkeptTailTokensByPreparation.get(preparation) ??\n\t\tMath.max(0, preparation.tokensBefore - preparation.region.tokenEstimate)\n\t);\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\" && typeof entry.summary === \"string\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction activeBoundary(entry: SessionEntry): entry is CompactionEntry<VerbatimCompactionDetails> {\n\tif (entry.type !== \"compaction\") return false;\n\tconst details = (entry as CompactionEntry<{ strategy?: string }>).details;\n\treturn details?.strategy === VERBATIM_COMPACTION_STRATEGY;\n}\n\nfunction visibleEntries(entries: SessionEntry[], start = 0): VisibleEntry[] {\n\tconst visible: VisibleEntry[] = [];\n\tfor (let index = start; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message && messageIsLlmVisible(message)) visible.push({ entry, index, message });\n\t}\n\treturn visible;\n}\n\nfunction messageText(message: AgentMessage): string {\n\tconst converted = convertToLlm([message]);\n\tif (converted.length === 0) return \"\";\n\treturn converted\n\t\t.flatMap((item) =>\n\t\t\ttypeof item.content === \"string\"\n\t\t\t\t? [item.content]\n\t\t\t\t: item.content.filter((block) => block.type === \"text\").map((block) => block.text),\n\t\t)\n\t\t.join(\"\\n\");\n}\n\nexport function autoDetectCompactionQuery(entries: readonly SessionEntry[]): string {\n\tconst normalized = normalizeDerivedSessionEntries(entries);\n\tfor (let index = normalized.length - 1; index >= 0; index--) {\n\t\tconst message = messageFromEntry(normalized[index]);\n\t\tif (!message || !messageStartsLlmUserTurn(message)) continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text) return normalizeCompactionQuery(text, COMPACTION_AUTO_QUERY);\n\t}\n\treturn COMPACTION_AUTO_QUERY;\n}\n\nfunction latestActiveBoundary(\n\tentries: SessionEntry[],\n): { entry: CompactionEntry<VerbatimCompactionDetails>; index: number } | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (activeBoundary(entry)) return { entry, index };\n\t}\n\treturn undefined;\n}\n\n/**\n * Planner eligibility, kept separate from boundary preparation.\n *\n * `MIN_COMPACTABLE_REGION_LINES` exists to stop repeated pointless *planned*\n * compaction. A load-bearing caller has a different problem: one oversized tool\n * result can blow the context window while producing fewer than 20 compactable\n * lines, and refusing to prepare a boundary there makes the \"always completes\"\n * guarantee hollow — the fresh rung and its tail-drop rule become unreachable.\n */\nexport interface CompactionBoundaryControl {\n\t/**\n\t * Prepare a boundary even when the region is below the planner minimum.\n\t * Only `load_bearing` callers set this; the runner routes such a region\n\t * straight to the fresh rung without invoking a planner.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\n/** Prepare the complete compactable transcript and its exact context-visible message tail. */\nexport function prepareCompactionBoundary(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: Partial<VerbatimCompactionParameters> = {},\n\tcontrol: CompactionBoundaryControl = {},\n): VerbatimCompactionPreparation | undefined {\n\tconst entries = normalizeDerivedSessionEntries(pathEntries);\n\tconst previous = latestActiveBoundary(entries);\n\tlet regionStart = 0;\n\tif (previous) {\n\t\tconst keptIndex =\n\t\t\tprevious.entry.firstKeptEntryId === null\n\t\t\t\t? -1\n\t\t\t\t: entries.findIndex((entry) => entry.id === previous.entry.firstKeptEntryId);\n\t\tregionStart = keptIndex >= 0 ? keptIndex : previous.index + 1;\n\t}\n\n\tconst visible = visibleEntries(entries, regionStart);\n\tconst parameters = normalizeCompactionParameters({ ...settings, ...options }, autoDetectCompactionQuery(entries));\n\tconst tailStart = Math.max(0, visible.length - parameters.preserve_recent);\n\tconst regionMessages = visible.slice(0, tailStart);\n\tconst tailMessages = visible.slice(tailStart);\n\n\tconst serialized = serializeConversationForCompaction(convertToLlm(regionMessages.map((item) => item.message)));\n\tconst regionText = [previous?.entry.summary, serialized]\n\t\t.filter((text): text is string => typeof text === \"string\" && text.length > 0)\n\t\t.join(\"\\n\");\n\tconst region = createNumberedRegion(regionText);\n\tif (!control.allowSmallRegion && region.lines.length < MIN_COMPACTABLE_REGION_LINES) return undefined;\n\n\tconst preparation: VerbatimCompactionPreparation = {\n\t\tfirstKeptEntryId: tailMessages[0]?.entry.id ?? null,\n\t\tregion,\n\t\tregionEntryIds: regionMessages.map((item) => item.entry.id),\n\t\tkeptTailMessageCount: tailMessages.length,\n\t\ttokensBefore: estimateContextTokens(buildSessionContext(entries).messages).tokens,\n\t\tparameters,\n\t\tsettings,\n\t};\n\tkeptTailTokensByPreparation.set(\n\t\tpreparation,\n\t\ttailMessages.reduce((sum, item) => sum + estimateTokens(item.message), 0),\n\t);\n\treturn preparation;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compaction-boundary.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-boundary.ts"],"names":[],"mappings":"AACA,OAAO,EACN,YAAY,EACZ,0BAA0B,EAC1B,mBAAmB,EACnB,mBAAmB,EACnB,wBAAwB,GACxB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,8BAA8B,EAAE,MAAM,mCAAmC,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEpE,OAAO,EAA2B,qBAAqB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjG,OAAO,EACN,qBAAqB,EACrB,6BAA6B,EAC7B,wBAAwB,GACxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACN,4BAA4B,EAC5B,4BAA4B,GAI5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,oBAAoB,EAAE,kCAAkC,EAAE,MAAM,+BAA+B,CAAC;AAQzG,MAAM,2BAA2B,GAAG,IAAI,OAAO,EAAyC,CAAC;AAEzF;;;;;;;;;;GAUG;AACH,MAAM,UAAU,wBAAwB,CAAC,WAA0C;IAClF,MAAM,UAAU,GAAG,2BAA2B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAChE,OAAO,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,C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AAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3D,oBAAoB,EAAE,YAAY,CAAC,MAAM;QACzC,YAAY,EAAE,qBAAqB,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM;QACjF,UAAU;QACV,QAAQ;KACR,CAAC;IACF,2BAA2B,CAAC,GAAG,CAC9B,WAAW,EACX,YAAY,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CACzE,CAAC;IACF,OAAO,WAAW,CAAC;AACpB,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCustomMessage,\n\tmessageIsLlmVisible,\n\tmessageStartsLlmUserTurn,\n} from \"../messages.ts\";\nimport { normalizeDerivedSessionEntries } from \"../session-entry-normalization.ts\";\nimport { buildSessionContext } from \"../session-manager-history.ts\";\nimport type { CompactionEntry, SessionEntry } from \"../session-manager-types.ts\";\nimport { type CompactionSettings, estimateContextTokens, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCOMPACTION_AUTO_QUERY,\n\tnormalizeCompactionParameters,\n\tnormalizeCompactionQuery,\n} from \"./compaction-parameters.js\";\nimport {\n\tMIN_COMPACTABLE_REGION_LINES,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionParameters,\n\ttype VerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { createNumberedRegion, serializeConversationForCompaction } from \"./transcript-serialization.js\";\n\ninterface VisibleEntry {\n\tentry: SessionEntry;\n\tindex: number;\n\tmessage: AgentMessage;\n}\n\nconst keptTailTokensByPreparation = new WeakMap<VerbatimCompactionPreparation, number>();\n\n/**\n * Return the independently estimated cost of the protected tail.\n *\n * Only the explicit estimate recorded by `prepareCompactionBoundary` (or a test)\n * is returned. The old fallback of `tokensBefore - region.tokenEstimate` was\n * removed because it mixed the authoritative whole-context count with the\n * heuristic region estimate; when no explicit estimate exists the tail simply\n * contributes nothing rather than a wrong-numbered value. Whether an estimate is\n * registered at all is visible through `hasKeptTailTokenEstimate`, which the\n * fresh rung uses to decide a tail whose size is unknown (P1 #3010).\n */\nexport function getKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): number {\n\tconst registered = keptTailTokensByPreparation.get(preparation);\n\treturn registered === undefined ? 0 : registered;\n}\n\n/**\n * Whether an independent tail estimate is registered for this preparation.\n *\n * A preparation built by `prepareCompactionBoundary` always has one. A directly\n * constructed preparation may not; the fresh rung treats a kept tail whose size\n * is unregistered as unknown and drops it conservatively rather than assuming it\n * fits (P1 #3010).\n */\nexport function hasKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): boolean {\n\treturn keptTailTokensByPreparation.has(preparation);\n}\n\n/**\n * Record the independent tail estimate for a preparation.\n *\n * `prepareCompactionBoundary` does this itself from the kept-tail messages;\n * this setter is for test preparations built directly and for any other code\n * that constructs a `VerbatimCompactionPreparation` without the boundary\n * preparer. The estimate lives in a module-private map and is never persisted.\n */\nexport function setKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation, estimate: number): void {\n\tkeptTailTokensByPreparation.set(preparation, Math.max(0, estimate));\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\" && typeof entry.summary === \"string\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction activeBoundary(entry: SessionEntry): entry is CompactionEntry<VerbatimCompactionDetails> {\n\tif (entry.type !== \"compaction\") return false;\n\tconst details = (entry as CompactionEntry<{ strategy?: string }>).details;\n\treturn details?.strategy === VERBATIM_COMPACTION_STRATEGY;\n}\n\nfunction visibleEntries(entries: SessionEntry[], start = 0): VisibleEntry[] {\n\tconst visible: VisibleEntry[] = [];\n\tfor (let index = start; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message && messageIsLlmVisible(message)) visible.push({ entry, index, message });\n\t}\n\treturn visible;\n}\n\nfunction messageText(message: AgentMessage): string {\n\tconst converted = convertToLlm([message]);\n\tif (converted.length === 0) return \"\";\n\treturn converted\n\t\t.flatMap((item) =>\n\t\t\ttypeof item.content === \"string\"\n\t\t\t\t? [item.content]\n\t\t\t\t: item.content.filter((block) => block.type === \"text\").map((block) => block.text),\n\t\t)\n\t\t.join(\"\\n\");\n}\n\nexport function autoDetectCompactionQuery(entries: readonly SessionEntry[]): string {\n\tconst normalized = normalizeDerivedSessionEntries(entries);\n\tfor (let index = normalized.length - 1; index >= 0; index--) {\n\t\tconst message = messageFromEntry(normalized[index]);\n\t\tif (!message || !messageStartsLlmUserTurn(message)) continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text) return normalizeCompactionQuery(text, COMPACTION_AUTO_QUERY);\n\t}\n\treturn COMPACTION_AUTO_QUERY;\n}\n\nfunction latestActiveBoundary(\n\tentries: SessionEntry[],\n): { entry: CompactionEntry<VerbatimCompactionDetails>; index: number } | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (activeBoundary(entry)) return { entry, index };\n\t}\n\treturn undefined;\n}\n\n/**\n * Planner eligibility, kept separate from boundary preparation.\n *\n * `MIN_COMPACTABLE_REGION_LINES` exists to stop repeated pointless *planned*\n * compaction. A load-bearing caller has a different problem: one oversized tool\n * result can blow the context window while producing fewer than 20 compactable\n * lines, and refusing to prepare a boundary there makes the \"always completes\"\n * guarantee hollow — the fresh rung and its tail-drop rule become unreachable.\n */\nexport interface CompactionBoundaryControl {\n\t/**\n\t * Prepare a boundary even when the region is below the planner minimum.\n\t * Only `load_bearing` callers set this; the runner routes such a region\n\t * straight to the fresh rung without invoking a planner.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\n/** Prepare the complete compactable transcript and its exact context-visible message tail. */\nexport function prepareCompactionBoundary(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: Partial<VerbatimCompactionParameters> = {},\n\tcontrol: CompactionBoundaryControl = {},\n): VerbatimCompactionPreparation | undefined {\n\tconst entries = normalizeDerivedSessionEntries(pathEntries);\n\tconst previous = latestActiveBoundary(entries);\n\tlet regionStart = 0;\n\tif (previous) {\n\t\tconst keptIndex =\n\t\t\tprevious.entry.firstKeptEntryId === null\n\t\t\t\t? -1\n\t\t\t\t: entries.findIndex((entry) => entry.id === previous.entry.firstKeptEntryId);\n\t\tregionStart = keptIndex >= 0 ? keptIndex : previous.index + 1;\n\t}\n\n\tconst visible = visibleEntries(entries, regionStart);\n\tconst parameters = normalizeCompactionParameters({ ...settings, ...options }, autoDetectCompactionQuery(entries));\n\tconst tailStart = Math.max(0, visible.length - parameters.preserve_recent);\n\tconst regionMessages = visible.slice(0, tailStart);\n\tconst tailMessages = visible.slice(tailStart);\n\n\tconst serialized = serializeConversationForCompaction(convertToLlm(regionMessages.map((item) => item.message)));\n\tconst regionText = [previous?.entry.summary, serialized]\n\t\t.filter((text): text is string => typeof text === \"string\" && text.length > 0)\n\t\t.join(\"\\n\");\n\tconst region = createNumberedRegion(regionText);\n\tif (!control.allowSmallRegion && region.lines.length < MIN_COMPACTABLE_REGION_LINES) return undefined;\n\n\tconst preparation: VerbatimCompactionPreparation = {\n\t\tfirstKeptEntryId: tailMessages[0]?.entry.id ?? null,\n\t\tregion,\n\t\tregionEntryIds: regionMessages.map((item) => item.entry.id),\n\t\tkeptTailMessageCount: tailMessages.length,\n\t\ttokensBefore: estimateContextTokens(buildSessionContext(entries).messages).tokens,\n\t\tparameters,\n\t\tsettings,\n\t};\n\tkeptTailTokensByPreparation.set(\n\t\tpreparation,\n\t\ttailMessages.reduce((sum, item) => sum + estimateTokens(item.message), 0),\n\t);\n\treturn preparation;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-runner.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAE7E,OAAO,KAAK,EAEX,mBAAmB,EACnB,sBAAsB,EACtB,iBAAiB,EACjB,WAAW,EAEX,6BAA6B,EAC7B,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAGN,KAAK,sBAAsB,EAE3B,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"compaction-runner.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAE7E,OAAO,KAAK,EAEX,mBAAmB,EACnB,sBAAsB,EACtB,iBAAiB,EACjB,WAAW,EAEX,6BAA6B,EAC7B,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAGN,KAAK,sBAAsB,EAE3B,MAAM,uBAAuB,CAAC;AAa/B,MAAM,WAAW,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./compaction-boundary.js";
|
|
1
|
+
import { getKeptTailTokenEstimate, hasKeptTailTokenEstimate } from "./compaction-boundary.js";
|
|
2
2
|
import { MIN_COMPACTABLE_REGION_LINES } from "./compaction-types.js";
|
|
3
3
|
import { reconstructCompactedTranscript, validateDeletedRanges } from "./deleted-ranges.js";
|
|
4
4
|
import { createFallbackPlannerBorrower, plannerAttemptKey, } from "./fallback-planner.js";
|
|
5
5
|
import { MALFORMED_OUTPUT_MESSAGE, NO_USABLE_RANGES_MESSAGE, planDeletedLineRanges, RangePlanError, resolvePlannerRequest, } from "./range-planner.js";
|
|
6
6
|
import { writeSuccessDiagnosticSidecar } from "./range-planner-diagnostics.js";
|
|
7
7
|
import { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from "./region-trimming.js";
|
|
8
|
+
import { widenToWholeContextStats } from "./whole-context-stats.js";
|
|
8
9
|
function addUsage(total, usage) {
|
|
9
10
|
const cacheWrite1h = (total?.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0);
|
|
10
11
|
const reasoning = (total?.reasoning ?? 0) + (usage.reasoning ?? 0);
|
|
@@ -47,12 +48,20 @@ export function targetKeepLines(preparation) {
|
|
|
47
48
|
function hardInputLimitFor(model) {
|
|
48
49
|
return model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;
|
|
49
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* Widen region-level transcript stats to whole-context stats (#2052).
|
|
53
|
+
*
|
|
54
|
+
* `result.stats` must be the symmetric region-only stats produced by
|
|
55
|
+
* `reconstructCompactedTranscript`; this adds the independently estimated kept
|
|
56
|
+
* tail to the heuristic before count on both sides — and, only when the tail is
|
|
57
|
+
* kept, to the after count — via the shared `widenToWholeContextStats`. The
|
|
58
|
+
* authoritative `preparation.tokensBefore` is deliberately absent from this
|
|
59
|
+
* comparison and travels separately for budgeting/display.
|
|
60
|
+
*/
|
|
50
61
|
function withWholeContextStats(result, preparation, keptTail) {
|
|
51
|
-
const tokensAfter = result.stats.tokensAfter + (keptTail ? getKeptTailTokenEstimate(preparation) : 0);
|
|
52
|
-
const percentReduction = preparation.tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / preparation.tokensBefore) * 1000) / 10;
|
|
53
62
|
return {
|
|
54
63
|
...result,
|
|
55
|
-
stats:
|
|
64
|
+
stats: widenToWholeContextStats(result.stats, getKeptTailTokenEstimate(preparation), keptTail),
|
|
56
65
|
};
|
|
57
66
|
}
|
|
58
67
|
/**
|
|
@@ -75,7 +84,11 @@ function buildFreshContextWindow(preparation, hardInputLimit) {
|
|
|
75
84
|
// way, and counting the reconstructed protected/marker text here would drop a
|
|
76
85
|
// tail that fits. A rebuilt context that still cannot be sent is the post-tool
|
|
77
86
|
// gate's problem, not a reason for this rung to discard more.
|
|
78
|
-
|
|
87
|
+
// A kept tail with no registered estimate (a directly constructed
|
|
88
|
+
// preparation) is dropped conservatively rather than assumed to fit (P1 #3010).
|
|
89
|
+
const keptTail = preparation.keptTailMessageCount === 0 ||
|
|
90
|
+
(hasKeptTailTokenEstimate(preparation) && getKeptTailTokenEstimate(preparation) <= limit);
|
|
91
|
+
return { transcript: buildFreshTranscript(preparation), keptTail };
|
|
79
92
|
}
|
|
80
93
|
/**
|
|
81
94
|
* Discard every compactable line and start a fresh context window.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAUpE,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,EAEN,6BAA6B,EAE7B,iBAAiB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EACN,wBAAwB,EACxB,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,EACd,qBAAq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Y,EAAE,YAAY,CAAC,CAAC;QAC/E,CAAC;QACD,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,SAAS,CAAC,GAAG,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC;QAC1C,OAAO,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC5E,QAAQ,GAAG,OAAO,KAAK,SAAS,CAAC;QACjC,IAAI,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAC9D,CAAC;IAED,IAAI,OAAO,CAAC,OAAO,KAAK,cAAc;QAAE,MAAM,aAAa,CAAC,YAAY,CAAC,CAAC;IAC1E,OAAO,WAAW,CAAC,WAAW,EAAE,cAAc,EAAE,YAAY,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type { RetryCallbacks, RetryPolicy } from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { getKeptTailTokenEstimate } from \"./compaction-boundary.js\";\nimport type {\n\tBorrowedPlanner,\n\tCompactedTranscript,\n\tCompactionPlannerModel,\n\tCompactionUrgency,\n\tPlannerAuth,\n\tRawLineRange,\n\tVerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { MIN_COMPACTABLE_REGION_LINES } from \"./compaction-types.js\";\nimport { reconstructCompactedTranscript, validateDeletedRanges } from \"./deleted-ranges.js\";\nimport {\n\ttype BorrowFallbackPlanner,\n\tcreateFallbackPlannerBorrower,\n\ttype FallbackPlannerContext,\n\tplannerAttemptKey,\n} from \"./fallback-planner.js\";\nimport type { TerminalPlannerOutcome } from \"./planner-outcome.js\";\nimport {\n\tMALFORMED_OUTPUT_MESSAGE,\n\tNO_USABLE_RANGES_MESSAGE,\n\tplanDeletedLineRanges,\n\tRangePlanError,\n\tresolvePlannerRequest,\n} from \"./range-planner.js\";\nimport { writeSuccessDiagnosticSidecar } from \"./range-planner-diagnostics.js\";\nimport { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from \"./region-trimming.js\";\n\nexport interface CompactionPlanOptions {\n\tstreamFn: StreamFn;\n\t/** Absolute path of the persisted session file. Undefined for in-memory sessions. */\n\tsessionFilePath?: string;\n\tretry?: RetryPolicy;\n\tcallbacks?: RetryCallbacks;\n}\n\n/** One compaction run's request. Urgency is required; there is no default. */\nexport interface CompactionRunRequest extends CompactionPlanOptions {\n\t/** Per-model credentials; a borrowed candidate uses its own, never the session model's. */\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tsignal?: AbortSignal;\n\t/** Inherited by the planner and never modified across attempts. */\n\tthinkingLevel: ThinkingLevel | undefined;\n\turgency: CompactionUrgency;\n\t/** Configured fallback candidates. Omitted means borrowing is impossible. */\n\tfallback?: FallbackPlannerContext;\n}\n\nexport type CompactionRungResult = CompactedTranscript & {\n\trung: \"planned\" | \"fresh\";\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** False only when the fresh rung had to drop the protected tail. */\n\tkeptTail: boolean;\n\t/** Aggregate usage across every planner request and retry in this run. */\n\tusage?: Usage;\n};\n\n/** Runner-internal fresh-window build: the transcript plus the tail decision. */\ninterface FreshWindowBuild {\n\ttranscript: CompactedTranscript;\n\tkeptTail: boolean;\n}\n\nfunction addUsage(total: Usage | undefined, usage: Usage): Usage {\n\tconst cacheWrite1h = (total?.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0);\n\tconst reasoning = (total?.reasoning ?? 0) + (usage.reasoning ?? 0);\n\treturn {\n\t\tinput: (total?.input ?? 0) + usage.input,\n\t\toutput: (total?.output ?? 0) + usage.output,\n\t\tcacheRead: (total?.cacheRead ?? 0) + usage.cacheRead,\n\t\tcacheWrite: (total?.cacheWrite ?? 0) + usage.cacheWrite,\n\t\t...(total?.cacheWrite1h !== undefined || usage.cacheWrite1h !== undefined ? { cacheWrite1h } : {}),\n\t\t...(total?.reasoning !== undefined || usage.reasoning !== undefined ? { reasoning } : {}),\n\t\ttotalTokens: (total?.totalTokens ?? 0) + usage.totalTokens,\n\t\tcost: {\n\t\t\tinput: (total?.cost.input ?? 0) + usage.cost.input,\n\t\t\toutput: (total?.cost.output ?? 0) + usage.cost.output,\n\t\t\tcacheRead: (total?.cost.cacheRead ?? 0) + usage.cost.cacheRead,\n\t\t\tcacheWrite: (total?.cost.cacheWrite ?? 0) + usage.cost.cacheWrite,\n\t\t\ttotal: (total?.cost.total ?? 0) + usage.cost.total,\n\t\t},\n\t};\n}\n\n/**\n * Calculate the single global line threshold from the prepared setting.\n *\n * Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5\n * ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the\n * compression ratio a real bound on output size, so protection can never enlarge the result.\n *\n * This is the untrimmed target. Overflow trimming does NOT reuse it:\n * `planWithTrimming` recomputes the threshold against each trimmed view, so the\n * planner is always asked to keep a proportion of the lines it actually\n * received rather than a proportion of a region it never saw.\n *\n * Retained as an exported helper for tests and consumers that need the\n * pre-trim target; production planning goes through `planWithTrimming`.\n */\nexport function targetKeepLines(preparation: VerbatimCompactionPreparation): number {\n\tconst region = preparation.region;\n\treturn Math.round(region.lines.length * preparation.parameters.compression_ratio);\n}\n\nfunction hardInputLimitFor(model: Model<Api>): number {\n\treturn model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n}\n\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\tconst tokensAfter = result.stats.tokensAfter + (keptTail ? getKeptTailTokenEstimate(preparation) : 0);\n\tconst percentReduction =\n\t\tpreparation.tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / preparation.tokensBefore) * 1000) / 10;\n\treturn {\n\t\t...result,\n\t\tstats: { ...result.stats, tokensBefore: preparation.tokensBefore, tokensAfter, percentReduction },\n\t};\n}\n\n/**\n * Build a fresh context window and the tail decision that goes with it.\n *\n * Private on purpose: `keptTail` is runner bookkeeping that persistence needs in\n * order to write `firstKeptEntryId: null` when the protected tail is dropped. It\n * is deliberately absent from the public door's return value, which is exactly a\n * `CompactedTranscript`.\n */\nfunction buildFreshTranscript(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\tconst region = preparation.region;\n\tconst whole: RawLineRange[] = region.lines.length > 0 ? [{ start: 1, end: region.lines.length }] : [];\n\treturn reconstructCompactedTranscript(region, validateDeletedRanges(whole, region));\n}\n\nfunction buildFreshContextWindow(preparation: VerbatimCompactionPreparation, hardInputLimit: number): FreshWindowBuild {\n\tconst limit = Number.isFinite(hardInputLimit) && hardInputLimit > 0 ? hardInputLimit : Number.POSITIVE_INFINITY;\n\t// The rule is \"tail under the limit ⇒ tail kept\", so the comparison is the\n\t// tail alone. Explicit protected lines are a hard floor that survives either\n\t// way, and counting the reconstructed protected/marker text here would drop a\n\t// tail that fits. A rebuilt context that still cannot be sent is the post-tool\n\t// gate's problem, not a reason for this rung to discard more.\n\treturn { transcript: buildFreshTranscript(preparation), keptTail: getKeptTailTokenEstimate(preparation) <= limit };\n}\n\n/**\n * Discard every compactable line and start a fresh context window.\n *\n * TOTAL. No provider, no credentials, no network, no signal, no failure mode,\n * no `Promise`. Port of codex `compact_token_budget` →\n * `Session::start_new_context_window`. Atomic's system prompt, context files,\n * and skills are rebuilt per request and were never in the transcript, so they\n * survive automatically.\n *\n * The whole region is emitted as one deletion range and handed to the unchanged\n * `validateDeletedRanges` → `reconstructCompactedTranscript` path, which splits\n * around protected spans and folds prior markers.\n *\n * Returns exactly a `CompactedTranscript` — `text`, `ranges`, `stats` and\n * nothing else. Whether the `preserve_recent` tail survives is a persistence\n * concern and travels on `CompactionRungResult.keptTail`, not on this door.\n */\nexport function startNewContextWindow(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\treturn buildFreshTranscript(preparation);\n}\n\nfunction plannedResult(\n\tpreparation: VerbatimCompactionPreparation,\n\tranges: RawLineRange[],\n\tplannerModel: CompactionPlannerModel | undefined,\n\tusage: Usage | undefined,\n): CompactionRungResult {\n\tconst reconstructed = reconstructCompactedTranscript(\n\t\tpreparation.region,\n\t\tvalidateDeletedRanges(ranges, preparation.region),\n\t);\n\treturn {\n\t\t...withWholeContextStats(reconstructed, preparation, true),\n\t\trung: \"planned\",\n\t\t...(plannerModel ? { plannerModel } : {}),\n\t\tkeptTail: true,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\nfunction borrowedIdentity(planner: BorrowedPlanner): CompactionPlannerModel {\n\treturn {\n\t\tprovider: planner.model.provider,\n\t\tid: planner.model.id,\n\t\t...(planner.budget.reasoning ? { thinkingLevel: planner.budget.reasoning } : {}),\n\t};\n}\n\nfunction terminalError(outcome: TerminalPlannerOutcome | undefined): RangePlanError {\n\tif (!outcome) return new RangePlanError(MALFORMED_OUTPUT_MESSAGE, 1, \"\", false);\n\tif (outcome.kind === \"rateLimited\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tif (outcome.kind === \"overflowed\") {\n\t\treturn new RangePlanError(\n\t\t\t\"Compaction range planning exceeded the model context window\",\n\t\t\t1,\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t\toutcome.diagnosticPath,\n\t\t\toutcome,\n\t\t);\n\t}\n\tif (outcome.kind === \"providerError\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tconst message = outcome.category === \"malformed_output\" ? MALFORMED_OUTPUT_MESSAGE : NO_USABLE_RANGES_MESSAGE;\n\treturn new RangePlanError(message, 1, outcome.excerpt, false, outcome.diagnosticPath, outcome);\n}\n\ntype PlannerAttempt =\n\t| { kind: \"planned\"; ranges: RawLineRange[] }\n\t| { kind: \"terminal\"; outcome: TerminalPlannerOutcome };\n\n/**\n * Run one planner model, retrying the same model after oldest-first input\n * trimming when the request itself overflows the context window.\n *\n * Trimming continues until no strictly smaller view exists; `nextTrimOffset`\n * halves the remaining suffix, so the walk is finite. Only then is `overflowed`\n * terminal and the ladder advances.\n *\n * Each view gets its own keep target from `compression_ratio`. Reusing the\n * original whole-preparation target is what asked a halved 20-line region to\n * keep 10 of its 10 visible lines — a request for zero deletions, whose obedient\n * empty answer then hits the non-negotiable zero-range rejection. Extra\n * reduction still comes only from the head the runner withheld.\n */\nasync function planWithTrimming(\n\tpreparation: VerbatimCompactionPreparation,\n\tplanner: BorrowedPlanner,\n\toptions: CompactionPlanOptions & { signal?: AbortSignal },\n): Promise<PlannerAttempt> {\n\tlet offset = 0;\n\tfor (;;) {\n\t\tconst region = offset === 0 ? preparation.region : trimRegionHead(preparation.region, offset);\n\t\tif (!region) return { kind: \"terminal\", outcome: { kind: \"overflowed\" } };\n\t\tconst keepTarget = Math.max(\n\t\t\tregion.protectedLineNumbers?.size ?? 0,\n\t\t\tMath.round(region.lines.length * preparation.parameters.compression_ratio),\n\t\t);\n\t\tconst outcome = await planDeletedLineRanges(region, preparation.parameters, planner, keepTarget, options);\n\t\tif (outcome.kind === \"ranked\" || outcome.kind === \"recovered\") {\n\t\t\tif (offset === 0) return { kind: \"planned\", ranges: outcome.ranges };\n\t\t\tconst validated = validateDeletedRanges(outcome.ranges, region);\n\t\t\treturn { kind: \"planned\", ranges: rebaseTrimmedRanges(validated, offset) };\n\t\t}\n\t\tif (outcome.kind !== \"overflowed\") return { kind: \"terminal\", outcome };\n\t\tif (options.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tconst next = nextTrimOffset(preparation.region, offset);\n\t\tif (next === undefined) return { kind: \"terminal\", outcome };\n\t\toffset = next;\n\t}\n}\n\nconst MISSING_AUTH_MESSAGE = \"Compaction provider authentication is unavailable\";\n\n/**\n * A runner-local terminal cause with no provider attempt behind it.\n *\n * Missing credentials are not a provider outcome — no request was made — so no\n * synthetic response is fabricated and no diagnostic sidecar is written. It is\n * carried as `providerError` purely so the ladder can advance past it.\n */\nfunction authFailureOutcome(error: unknown): TerminalPlannerOutcome {\n\tconst message = error instanceof Error ? error.message : error === undefined ? MISSING_AUTH_MESSAGE : String(error);\n\treturn { kind: \"providerError\", message: message || MISSING_AUTH_MESSAGE };\n}\n\n/** Resolve one model's credentials, normalizing a rejection and `undefined` alike. */\nasync function resolvePlannerAuth(\n\tresolveAuth: CompactionRunRequest[\"resolveAuth\"],\n\tmodel: Model<Api>,\n): Promise<{ auth: PlannerAuth } | { failure: TerminalPlannerOutcome }> {\n\ttry {\n\t\tconst auth = await resolveAuth(model);\n\t\treturn auth ? { auth } : { failure: authFailureOutcome(undefined) };\n\t} catch (error) {\n\t\treturn { failure: authFailureOutcome(error) };\n\t}\n}\n\nfunction freshResult(\n\tpreparation: VerbatimCompactionPreparation,\n\thardInputLimit: number,\n\tusage?: Usage,\n): CompactionRungResult {\n\tconst fresh = buildFreshContextWindow(preparation, hardInputLimit);\n\treturn {\n\t\t...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),\n\t\trung: \"fresh\",\n\t\tkeptTail: fresh.keptTail,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\n/**\n * Produce one compacted transcript, tagged with the rung that produced it.\n *\n * The ladder is: the session model, then each configured fallback model\n * borrowed for one planner request, then — only under `load_bearing` urgency —\n * a fresh context window. A manual `/compact` runs at `recoverable` urgency and\n * therefore cannot reach the context-destroying rung; it fails honestly instead.\n *\n * Unavailable credentials are ladder control flow, not an early throw: a\n * borrowed candidate with its own working credentials can still rank the lines,\n * and a load-bearing caller still reaches the credential-free fresh rung.\n */\nexport async function runVerbatimCompaction(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n): Promise<CompactionRungResult> {\n\tconst signal = request.signal;\n\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tlet plannerUsage: Usage | undefined;\n\tconst plannerOptions = {\n\t\tstreamFn: request.streamFn,\n\t\tsessionFilePath: request.sessionFilePath,\n\t\tretry: request.retry,\n\t\tcallbacks: request.callbacks,\n\t\tsignal,\n\t\tonUsage: (usage: Usage) => {\n\t\t\tplannerUsage = addUsage(plannerUsage, usage);\n\t\t},\n\t};\n\tconst hardInputLimit = hardInputLimitFor(model);\n\n\t// A region below the planner minimum cannot be made rankable by changing\n\t// models, so no planner is invoked. Only a load-bearing caller can reach a\n\t// preparation this small; recoverable callers were refused before the runner.\n\tif (preparation.region.lines.length < MIN_COMPACTABLE_REGION_LINES) {\n\t\tif (request.urgency !== \"load_bearing\") throw new RangePlanError(NO_USABLE_RANGES_MESSAGE, 0, \"\", false);\n\t\treturn freshResult(preparation, hardInputLimit);\n\t}\n\n\tconst attempted = new Set<string>();\n\t// One borrower per run owns the monotonic cursor, so the configured list is\n\t// walked exactly once no matter how many terminal outcomes occur.\n\tconst borrow: BorrowFallbackPlanner | undefined = request.fallback\n\t\t? createFallbackPlannerBorrower(request.fallback)\n\t\t: undefined;\n\tconst primaryBudget = resolvePlannerRequest(model, request.thinkingLevel);\n\tconst primaryAuth = await resolvePlannerAuth(request.resolveAuth, model);\n\tlet lastTerminal: TerminalPlannerOutcome | undefined = \"failure\" in primaryAuth ? primaryAuth.failure : undefined;\n\tlet borrowed = false;\n\tlet planner: BorrowedPlanner | undefined;\n\n\tif (\"auth\" in primaryAuth) {\n\t\tplanner = { model, budget: primaryBudget, auth: primaryAuth.auth };\n\t} else {\n\t\t// No request was made, but this candidate must not be retried.\n\t\tattempted.add(plannerAttemptKey({ model, budget: primaryBudget, auth: {} }));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t}\n\n\twhile (planner) {\n\t\tconst attempt = await planWithTrimming(preparation, planner, plannerOptions);\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (attempt.kind === \"planned\") {\n\t\t\tconst plannerModel = borrowed ? borrowedIdentity(planner) : undefined;\n\t\t\tif (plannerModel) {\n\t\t\t\t// Best-effort: the durable entry already records the borrowed model;\n\t\t\t\t// a sidecar write failure never affects compaction success.\n\t\t\t\twriteSuccessDiagnosticSidecar({\n\t\t\t\t\tsessionFilePath: request.sessionFilePath,\n\t\t\t\t\tmodel: planner.model,\n\t\t\t\t\tsuccessCategory: \"borrowed_planner\",\n\t\t\t\t\t...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn plannedResult(preparation, attempt.ranges, plannerModel, plannerUsage);\n\t\t}\n\t\tlastTerminal = attempt.outcome;\n\t\tattempted.add(plannerAttemptKey(planner));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\tif (request.urgency !== \"load_bearing\") throw terminalError(lastTerminal);\n\treturn freshResult(preparation, hardInputLimit, plannerUsage);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAU9F,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,EAEN,6BAA6B,EAE7B,iBAAiB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EACN,wBAAwB,EACxB,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,EACd,qBAAqB,GACrB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,c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AO,KAAK,SAAS,CAAC;QACjC,IAAI,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAC9D,CAAC;IAED,IAAI,OAAO,CAAC,OAAO,KAAK,cAAc;QAAE,MAAM,aAAa,CAAC,YAAY,CAAC,CAAC;IAC1E,OAAO,WAAW,CAAC,WAAW,EAAE,cAAc,EAAE,YAAY,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type { RetryCallbacks, RetryPolicy } from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { getKeptTailTokenEstimate, hasKeptTailTokenEstimate } from \"./compaction-boundary.js\";\nimport type {\n\tBorrowedPlanner,\n\tCompactedTranscript,\n\tCompactionPlannerModel,\n\tCompactionUrgency,\n\tPlannerAuth,\n\tRawLineRange,\n\tVerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { MIN_COMPACTABLE_REGION_LINES } from \"./compaction-types.js\";\nimport { reconstructCompactedTranscript, validateDeletedRanges } from \"./deleted-ranges.js\";\nimport {\n\ttype BorrowFallbackPlanner,\n\tcreateFallbackPlannerBorrower,\n\ttype FallbackPlannerContext,\n\tplannerAttemptKey,\n} from \"./fallback-planner.js\";\nimport type { TerminalPlannerOutcome } from \"./planner-outcome.js\";\nimport {\n\tMALFORMED_OUTPUT_MESSAGE,\n\tNO_USABLE_RANGES_MESSAGE,\n\tplanDeletedLineRanges,\n\tRangePlanError,\n\tresolvePlannerRequest,\n} from \"./range-planner.js\";\nimport { writeSuccessDiagnosticSidecar } from \"./range-planner-diagnostics.js\";\nimport { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from \"./region-trimming.js\";\nimport { widenToWholeContextStats } from \"./whole-context-stats.js\";\n\nexport interface CompactionPlanOptions {\n\tstreamFn: StreamFn;\n\t/** Absolute path of the persisted session file. Undefined for in-memory sessions. */\n\tsessionFilePath?: string;\n\tretry?: RetryPolicy;\n\tcallbacks?: RetryCallbacks;\n}\n\n/** One compaction run's request. Urgency is required; there is no default. */\nexport interface CompactionRunRequest extends CompactionPlanOptions {\n\t/** Per-model credentials; a borrowed candidate uses its own, never the session model's. */\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tsignal?: AbortSignal;\n\t/** Inherited by the planner and never modified across attempts. */\n\tthinkingLevel: ThinkingLevel | undefined;\n\turgency: CompactionUrgency;\n\t/** Configured fallback candidates. Omitted means borrowing is impossible. */\n\tfallback?: FallbackPlannerContext;\n}\n\nexport type CompactionRungResult = CompactedTranscript & {\n\trung: \"planned\" | \"fresh\";\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** False only when the fresh rung had to drop the protected tail. */\n\tkeptTail: boolean;\n\t/** Aggregate usage across every planner request and retry in this run. */\n\tusage?: Usage;\n};\n\n/** Runner-internal fresh-window build: the transcript plus the tail decision. */\ninterface FreshWindowBuild {\n\ttranscript: CompactedTranscript;\n\tkeptTail: boolean;\n}\n\nfunction addUsage(total: Usage | undefined, usage: Usage): Usage {\n\tconst cacheWrite1h = (total?.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0);\n\tconst reasoning = (total?.reasoning ?? 0) + (usage.reasoning ?? 0);\n\treturn {\n\t\tinput: (total?.input ?? 0) + usage.input,\n\t\toutput: (total?.output ?? 0) + usage.output,\n\t\tcacheRead: (total?.cacheRead ?? 0) + usage.cacheRead,\n\t\tcacheWrite: (total?.cacheWrite ?? 0) + usage.cacheWrite,\n\t\t...(total?.cacheWrite1h !== undefined || usage.cacheWrite1h !== undefined ? { cacheWrite1h } : {}),\n\t\t...(total?.reasoning !== undefined || usage.reasoning !== undefined ? { reasoning } : {}),\n\t\ttotalTokens: (total?.totalTokens ?? 0) + usage.totalTokens,\n\t\tcost: {\n\t\t\tinput: (total?.cost.input ?? 0) + usage.cost.input,\n\t\t\toutput: (total?.cost.output ?? 0) + usage.cost.output,\n\t\t\tcacheRead: (total?.cost.cacheRead ?? 0) + usage.cost.cacheRead,\n\t\t\tcacheWrite: (total?.cost.cacheWrite ?? 0) + usage.cost.cacheWrite,\n\t\t\ttotal: (total?.cost.total ?? 0) + usage.cost.total,\n\t\t},\n\t};\n}\n\n/**\n * Calculate the single global line threshold from the prepared setting.\n *\n * Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5\n * ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the\n * compression ratio a real bound on output size, so protection can never enlarge the result.\n *\n * This is the untrimmed target. Overflow trimming does NOT reuse it:\n * `planWithTrimming` recomputes the threshold against each trimmed view, so the\n * planner is always asked to keep a proportion of the lines it actually\n * received rather than a proportion of a region it never saw.\n *\n * Retained as an exported helper for tests and consumers that need the\n * pre-trim target; production planning goes through `planWithTrimming`.\n */\nexport function targetKeepLines(preparation: VerbatimCompactionPreparation): number {\n\tconst region = preparation.region;\n\treturn Math.round(region.lines.length * preparation.parameters.compression_ratio);\n}\n\nfunction hardInputLimitFor(model: Model<Api>): number {\n\treturn model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n}\n\n/**\n * Widen region-level transcript stats to whole-context stats (#2052).\n *\n * `result.stats` must be the symmetric region-only stats produced by\n * `reconstructCompactedTranscript`; this adds the independently estimated kept\n * tail to the heuristic before count on both sides — and, only when the tail is\n * kept, to the after count — via the shared `widenToWholeContextStats`. The\n * authoritative `preparation.tokensBefore` is deliberately absent from this\n * comparison and travels separately for budgeting/display.\n */\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\treturn {\n\t\t...result,\n\t\tstats: widenToWholeContextStats(result.stats, getKeptTailTokenEstimate(preparation), keptTail),\n\t};\n}\n\n/**\n * Build a fresh context window and the tail decision that goes with it.\n *\n * Private on purpose: `keptTail` is runner bookkeeping that persistence needs in\n * order to write `firstKeptEntryId: null` when the protected tail is dropped. It\n * is deliberately absent from the public door's return value, which is exactly a\n * `CompactedTranscript`.\n */\nfunction buildFreshTranscript(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\tconst region = preparation.region;\n\tconst whole: RawLineRange[] = region.lines.length > 0 ? [{ start: 1, end: region.lines.length }] : [];\n\treturn reconstructCompactedTranscript(region, validateDeletedRanges(whole, region));\n}\n\nfunction buildFreshContextWindow(preparation: VerbatimCompactionPreparation, hardInputLimit: number): FreshWindowBuild {\n\tconst limit = Number.isFinite(hardInputLimit) && hardInputLimit > 0 ? hardInputLimit : Number.POSITIVE_INFINITY;\n\t// The rule is \"tail under the limit ⇒ tail kept\", so the comparison is the\n\t// tail alone. Explicit protected lines are a hard floor that survives either\n\t// way, and counting the reconstructed protected/marker text here would drop a\n\t// tail that fits. A rebuilt context that still cannot be sent is the post-tool\n\t// gate's problem, not a reason for this rung to discard more.\n\t// A kept tail with no registered estimate (a directly constructed\n\t// preparation) is dropped conservatively rather than assumed to fit (P1 #3010).\n\tconst keptTail =\n\t\tpreparation.keptTailMessageCount === 0 ||\n\t\t(hasKeptTailTokenEstimate(preparation) && getKeptTailTokenEstimate(preparation) <= limit);\n\treturn { transcript: buildFreshTranscript(preparation), keptTail };\n}\n\n/**\n * Discard every compactable line and start a fresh context window.\n *\n * TOTAL. No provider, no credentials, no network, no signal, no failure mode,\n * no `Promise`. Port of codex `compact_token_budget` →\n * `Session::start_new_context_window`. Atomic's system prompt, context files,\n * and skills are rebuilt per request and were never in the transcript, so they\n * survive automatically.\n *\n * The whole region is emitted as one deletion range and handed to the unchanged\n * `validateDeletedRanges` → `reconstructCompactedTranscript` path, which splits\n * around protected spans and folds prior markers.\n *\n * Returns exactly a `CompactedTranscript` — `text`, `ranges`, `stats` and\n * nothing else. Whether the `preserve_recent` tail survives is a persistence\n * concern and travels on `CompactionRungResult.keptTail`, not on this door.\n */\nexport function startNewContextWindow(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\treturn buildFreshTranscript(preparation);\n}\n\nfunction plannedResult(\n\tpreparation: VerbatimCompactionPreparation,\n\tranges: RawLineRange[],\n\tplannerModel: CompactionPlannerModel | undefined,\n\tusage: Usage | undefined,\n): CompactionRungResult {\n\tconst reconstructed = reconstructCompactedTranscript(\n\t\tpreparation.region,\n\t\tvalidateDeletedRanges(ranges, preparation.region),\n\t);\n\treturn {\n\t\t...withWholeContextStats(reconstructed, preparation, true),\n\t\trung: \"planned\",\n\t\t...(plannerModel ? { plannerModel } : {}),\n\t\tkeptTail: true,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\nfunction borrowedIdentity(planner: BorrowedPlanner): CompactionPlannerModel {\n\treturn {\n\t\tprovider: planner.model.provider,\n\t\tid: planner.model.id,\n\t\t...(planner.budget.reasoning ? { thinkingLevel: planner.budget.reasoning } : {}),\n\t};\n}\n\nfunction terminalError(outcome: TerminalPlannerOutcome | undefined): RangePlanError {\n\tif (!outcome) return new RangePlanError(MALFORMED_OUTPUT_MESSAGE, 1, \"\", false);\n\tif (outcome.kind === \"rateLimited\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tif (outcome.kind === \"overflowed\") {\n\t\treturn new RangePlanError(\n\t\t\t\"Compaction range planning exceeded the model context window\",\n\t\t\t1,\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t\toutcome.diagnosticPath,\n\t\t\toutcome,\n\t\t);\n\t}\n\tif (outcome.kind === \"providerError\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tconst message = outcome.category === \"malformed_output\" ? MALFORMED_OUTPUT_MESSAGE : NO_USABLE_RANGES_MESSAGE;\n\treturn new RangePlanError(message, 1, outcome.excerpt, false, outcome.diagnosticPath, outcome);\n}\n\ntype PlannerAttempt =\n\t| { kind: \"planned\"; ranges: RawLineRange[] }\n\t| { kind: \"terminal\"; outcome: TerminalPlannerOutcome };\n\n/**\n * Run one planner model, retrying the same model after oldest-first input\n * trimming when the request itself overflows the context window.\n *\n * Trimming continues until no strictly smaller view exists; `nextTrimOffset`\n * halves the remaining suffix, so the walk is finite. Only then is `overflowed`\n * terminal and the ladder advances.\n *\n * Each view gets its own keep target from `compression_ratio`. Reusing the\n * original whole-preparation target is what asked a halved 20-line region to\n * keep 10 of its 10 visible lines — a request for zero deletions, whose obedient\n * empty answer then hits the non-negotiable zero-range rejection. Extra\n * reduction still comes only from the head the runner withheld.\n */\nasync function planWithTrimming(\n\tpreparation: VerbatimCompactionPreparation,\n\tplanner: BorrowedPlanner,\n\toptions: CompactionPlanOptions & { signal?: AbortSignal },\n): Promise<PlannerAttempt> {\n\tlet offset = 0;\n\tfor (;;) {\n\t\tconst region = offset === 0 ? preparation.region : trimRegionHead(preparation.region, offset);\n\t\tif (!region) return { kind: \"terminal\", outcome: { kind: \"overflowed\" } };\n\t\tconst keepTarget = Math.max(\n\t\t\tregion.protectedLineNumbers?.size ?? 0,\n\t\t\tMath.round(region.lines.length * preparation.parameters.compression_ratio),\n\t\t);\n\t\tconst outcome = await planDeletedLineRanges(region, preparation.parameters, planner, keepTarget, options);\n\t\tif (outcome.kind === \"ranked\" || outcome.kind === \"recovered\") {\n\t\t\tif (offset === 0) return { kind: \"planned\", ranges: outcome.ranges };\n\t\t\tconst validated = validateDeletedRanges(outcome.ranges, region);\n\t\t\treturn { kind: \"planned\", ranges: rebaseTrimmedRanges(validated, offset) };\n\t\t}\n\t\tif (outcome.kind !== \"overflowed\") return { kind: \"terminal\", outcome };\n\t\tif (options.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tconst next = nextTrimOffset(preparation.region, offset);\n\t\tif (next === undefined) return { kind: \"terminal\", outcome };\n\t\toffset = next;\n\t}\n}\n\nconst MISSING_AUTH_MESSAGE = \"Compaction provider authentication is unavailable\";\n\n/**\n * A runner-local terminal cause with no provider attempt behind it.\n *\n * Missing credentials are not a provider outcome — no request was made — so no\n * synthetic response is fabricated and no diagnostic sidecar is written. It is\n * carried as `providerError` purely so the ladder can advance past it.\n */\nfunction authFailureOutcome(error: unknown): TerminalPlannerOutcome {\n\tconst message = error instanceof Error ? error.message : error === undefined ? MISSING_AUTH_MESSAGE : String(error);\n\treturn { kind: \"providerError\", message: message || MISSING_AUTH_MESSAGE };\n}\n\n/** Resolve one model's credentials, normalizing a rejection and `undefined` alike. */\nasync function resolvePlannerAuth(\n\tresolveAuth: CompactionRunRequest[\"resolveAuth\"],\n\tmodel: Model<Api>,\n): Promise<{ auth: PlannerAuth } | { failure: TerminalPlannerOutcome }> {\n\ttry {\n\t\tconst auth = await resolveAuth(model);\n\t\treturn auth ? { auth } : { failure: authFailureOutcome(undefined) };\n\t} catch (error) {\n\t\treturn { failure: authFailureOutcome(error) };\n\t}\n}\n\nfunction freshResult(\n\tpreparation: VerbatimCompactionPreparation,\n\thardInputLimit: number,\n\tusage?: Usage,\n): CompactionRungResult {\n\tconst fresh = buildFreshContextWindow(preparation, hardInputLimit);\n\treturn {\n\t\t...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),\n\t\trung: \"fresh\",\n\t\tkeptTail: fresh.keptTail,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\n/**\n * Produce one compacted transcript, tagged with the rung that produced it.\n *\n * The ladder is: the session model, then each configured fallback model\n * borrowed for one planner request, then — only under `load_bearing` urgency —\n * a fresh context window. A manual `/compact` runs at `recoverable` urgency and\n * therefore cannot reach the context-destroying rung; it fails honestly instead.\n *\n * Unavailable credentials are ladder control flow, not an early throw: a\n * borrowed candidate with its own working credentials can still rank the lines,\n * and a load-bearing caller still reaches the credential-free fresh rung.\n */\nexport async function runVerbatimCompaction(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n): Promise<CompactionRungResult> {\n\tconst signal = request.signal;\n\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tlet plannerUsage: Usage | undefined;\n\tconst plannerOptions = {\n\t\tstreamFn: request.streamFn,\n\t\tsessionFilePath: request.sessionFilePath,\n\t\tretry: request.retry,\n\t\tcallbacks: request.callbacks,\n\t\tsignal,\n\t\tonUsage: (usage: Usage) => {\n\t\t\tplannerUsage = addUsage(plannerUsage, usage);\n\t\t},\n\t};\n\tconst hardInputLimit = hardInputLimitFor(model);\n\n\t// A region below the planner minimum cannot be made rankable by changing\n\t// models, so no planner is invoked. Only a load-bearing caller can reach a\n\t// preparation this small; recoverable callers were refused before the runner.\n\tif (preparation.region.lines.length < MIN_COMPACTABLE_REGION_LINES) {\n\t\tif (request.urgency !== \"load_bearing\") throw new RangePlanError(NO_USABLE_RANGES_MESSAGE, 0, \"\", false);\n\t\treturn freshResult(preparation, hardInputLimit);\n\t}\n\n\tconst attempted = new Set<string>();\n\t// One borrower per run owns the monotonic cursor, so the configured list is\n\t// walked exactly once no matter how many terminal outcomes occur.\n\tconst borrow: BorrowFallbackPlanner | undefined = request.fallback\n\t\t? createFallbackPlannerBorrower(request.fallback)\n\t\t: undefined;\n\tconst primaryBudget = resolvePlannerRequest(model, request.thinkingLevel);\n\tconst primaryAuth = await resolvePlannerAuth(request.resolveAuth, model);\n\tlet lastTerminal: TerminalPlannerOutcome | undefined = \"failure\" in primaryAuth ? primaryAuth.failure : undefined;\n\tlet borrowed = false;\n\tlet planner: BorrowedPlanner | undefined;\n\n\tif (\"auth\" in primaryAuth) {\n\t\tplanner = { model, budget: primaryBudget, auth: primaryAuth.auth };\n\t} else {\n\t\t// No request was made, but this candidate must not be retried.\n\t\tattempted.add(plannerAttemptKey({ model, budget: primaryBudget, auth: {} }));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t}\n\n\twhile (planner) {\n\t\tconst attempt = await planWithTrimming(preparation, planner, plannerOptions);\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (attempt.kind === \"planned\") {\n\t\t\tconst plannerModel = borrowed ? borrowedIdentity(planner) : undefined;\n\t\t\tif (plannerModel) {\n\t\t\t\t// Best-effort: the durable entry already records the borrowed model;\n\t\t\t\t// a sidecar write failure never affects compaction success.\n\t\t\t\twriteSuccessDiagnosticSidecar({\n\t\t\t\t\tsessionFilePath: request.sessionFilePath,\n\t\t\t\t\tmodel: planner.model,\n\t\t\t\t\tsuccessCategory: \"borrowed_planner\",\n\t\t\t\t\t...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn plannedResult(preparation, attempt.ranges, plannerModel, plannerUsage);\n\t\t}\n\t\tlastTerminal = attempt.outcome;\n\t\tattempted.add(plannerAttemptKey(planner));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\tif (request.urgency !== \"load_bearing\") throw terminalError(lastTerminal);\n\treturn freshResult(preparation, hardInputLimit, plannerUsage);\n}\n"]}
|
|
@@ -108,6 +108,13 @@ export interface VerbatimCompactionDetails {
|
|
|
108
108
|
parameters: VerbatimCompactionParameters;
|
|
109
109
|
stats: VerbatimCompactionStats;
|
|
110
110
|
rung: CompactionRung;
|
|
111
|
+
/**
|
|
112
|
+
* Authoritative whole-context count, projected for display only. Populated by
|
|
113
|
+
* `createVerbatimCompactionMessage` on the rendered message; it is not
|
|
114
|
+
* persisted here — the durable entry already carries it as
|
|
115
|
+
* `CompactionEntry.tokensBefore`.
|
|
116
|
+
*/
|
|
117
|
+
tokensBefore?: number;
|
|
111
118
|
/** Present only when a borrowed fallback model ranked the lines. */
|
|
112
119
|
plannerModel?: CompactionPlannerModel;
|
|
113
120
|
backupPath?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-types.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE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AED,iFAAiF;AACjF,MAAM,WAAW,sBAAsB;IACtC,QAAQ,EAAE,MAAM,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,aAAa,CAAC,EAAE,aAAa,CAAC;CAC9B;AAED,MAAM,WAAW,yBAAyB;IACzC,QAAQ,EAAE,OAAO,4BAA4B,CAAC;IAC9C,aAAa,EAAE,OAAO,kCAAkC,CAAC;IACzD,UAAU,EAAE,4BAA4B,CAAC;IACzC,KAAK,EAAE,uBAAuB,CAAC;IAC/B,IAAI,EAAE,cAAc,CAAC;IACrB,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,6BAA6B;IAC7C,0FAA0F;IAC1F,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,MAAM,EAAE,cAAc,CAAC;IACvB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,4BAA4B,CAAC;IACzC,QAAQ,EAAE,kBAAkB,CAAC;CAC7B;AAED,MAAM,WAAW,wBAAwB;IACxC,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,uBAAuB,CAAC;IAC/B,UAAU,EAAE,4BAA4B,CAAC;IACzC,aAAa,EAAE,OAAO,kCAAkC,CAAC;IACzD,IAAI,EAAE,cAAc,CAAC;IACrB,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,iFAAiF;IACjF,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB"}
|
|
1
|
+
{"version":3,"file":"compaction-types.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"A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|
|
|
1
|
-
{"version":3,"file":"compaction-types.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAU,CAAC;AAC7D,MAAM,CAAC,MAAM,4BAA4B,GAAG,gBAAyB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { CompactionSettings } from \"./compaction.ts\";\n\nexport const VERBATIM_COMPACTION_PROMPT_VERSION = 3 as const;\nexport const VERBATIM_COMPACTION_STRATEGY = \"verbatim-lines\" as const;\n\nexport const DEFAULT_COMPRESSION_RATIO = 0.5;\nexport const DEFAULT_PRESERVE_RECENT = 2;\nexport const MIN_COMPACTABLE_REGION_LINES = 20;\n\nexport interface VerbatimCompactionParameters {\n\t/** Fraction of compactable region lines to keep. */\n\tcompression_ratio: number;\n\t/** Recent context-eligible messages retained outside the compactable region. */\n\tpreserve_recent: number;\n\t/** Relevance focus used by the range planner. */\n\tquery: string;\n}\n\nexport interface LineRange {\n\t/** One-based inclusive first line. */\n\tstart: number;\n\t/** One-based inclusive last line. */\n\tend: number;\n}\n\nexport type RawLineEndpoint = number | string | boolean | null;\n\nexport interface RawLineRange {\n\tstart?: RawLineEndpoint;\n\tend?: RawLineEndpoint;\n}\n\nexport interface NumberedRegion {\n\treadonly __brand: \"NumberedRegion\";\n\tlines: string[];\n\theaderLineNumbers: ReadonlySet<number>;\n\tpriorMarkerNs: ReadonlyMap<number, number>;\n\t/** Optional future protected spans, expressed as one-based line numbers. */\n\tprotectedLineNumbers?: ReadonlySet<number>;\n\ttokenEstimate: number;\n}\n\nexport type ValidatedRanges = readonly LineRange[] & { readonly __brand: \"ValidatedRanges\" };\n\nexport interface CompactedTranscript {\n\ttext: string;\n\tranges: LineRange[];\n\t/**\n\t * Ranges force-preserved by `<keepContext>` protection; empty when nothing was protected.\n\t * Reported so protection that fired unexpectedly — a transcript that quotes tag text, say —\n\t * is diagnosable rather than a silent reduction in what compaction reclaimed.\n\t */\n\tkeptRanges: LineRange[];\n\tstats: VerbatimCompactionStats;\n}\n\nexport interface VerbatimCompactionStats {\n\tlinesBefore: number;\n\tlinesDeleted: number;\n\tlinesKept: number;\n\trangeCount: number;\n\ttokensBefore: number;\n\ttokensAfter: number;\n\tpercentReduction: number;\n}\n\n/** How much the caller can afford to lose if compaction does not happen. */\nexport type CompactionUrgency =\n\t/** Manual /compact, threshold auto-compaction — failing is safe. */\n\t| \"recoverable\"\n\t/** Overflow recovery, post-tool preflight — failing kills the turn. */\n\t| \"load_bearing\";\n\n/** How a durable compaction boundary was produced. */\nexport type CompactionRung = \"planned\" | \"extension\" | \"fresh\";\n\n/** Credentials for one planner request. Resolved per model, never shared. */\nexport interface PlannerAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * What one planner request may spend.\n *\n * `maxTokens` is declared `undefined`, not `number | undefined`: the type\n * forbids reintroducing the `0.8 * reserveTokens` output cap without changing\n * the type and failing review. pi-ai's `clampMaxTokensToContext` is the only bound.\n */\nexport interface PlannerBudget {\n\treadonly maxTokens: undefined;\n\treadonly reasoning: ThinkingLevel | undefined;\n}\n\n/**\n * A planner-only model borrowing. Cannot be confused with a session model switch.\n *\n * It carries no attempted-set key: the effective identity of an attempt is\n * `provider/model:<effective reasoning>`, derived from `model` and\n * `budget.reasoning` by `plannerAttemptKey`. Storing a key resolved from the raw\n * optional suffix would let the same effective request run twice.\n */\nexport interface BorrowedPlanner {\n\treadonly model: Model<Api>;\n\treadonly budget: PlannerBudget;\n\treadonly auth: PlannerAuth;\n}\n\n/** Identity of the model that ranked the deleted lines, when it was borrowed. */\nexport interface CompactionPlannerModel {\n\tprovider: string;\n\tid: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport interface VerbatimCompactionDetails {\n\tstrategy: typeof VERBATIM_COMPACTION_STRATEGY;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\tparameters: VerbatimCompactionParameters;\n\tstats: VerbatimCompactionStats;\n\trung: CompactionRung;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\tbackupPath?: string;\n}\n\nexport interface VerbatimCompactionPreparation {\n\t/** First context-visible tail entry, or null when no pre-boundary message is retained. */\n\tfirstKeptEntryId: string | null;\n\tregion: NumberedRegion;\n\tregionEntryIds: string[];\n\tkeptTailMessageCount: number;\n\ttokensBefore: number;\n\tparameters: VerbatimCompactionParameters;\n\tsettings: CompactionSettings;\n}\n\nexport interface VerbatimCompactionResult {\n\tcompactedText: string;\n\tfirstKeptEntryId: string | null;\n\ttokensBefore: number;\n\tstats: VerbatimCompactionStats;\n\tparameters: VerbatimCompactionParameters;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\trung: CompactionRung;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** Aggregate usage across every planner request and retry in this compaction. */\n\tusage?: Usage;\n\tbackupPath?: string;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compaction-types.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAU,CAAC;AAC7D,MAAM,CAAC,MAAM,4BAA4B,GAAG,gBAAyB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { CompactionSettings } from \"./compaction.ts\";\n\nexport const VERBATIM_COMPACTION_PROMPT_VERSION = 3 as const;\nexport const VERBATIM_COMPACTION_STRATEGY = \"verbatim-lines\" as const;\n\nexport const DEFAULT_COMPRESSION_RATIO = 0.5;\nexport const DEFAULT_PRESERVE_RECENT = 2;\nexport const MIN_COMPACTABLE_REGION_LINES = 20;\n\nexport interface VerbatimCompactionParameters {\n\t/** Fraction of compactable region lines to keep. */\n\tcompression_ratio: number;\n\t/** Recent context-eligible messages retained outside the compactable region. */\n\tpreserve_recent: number;\n\t/** Relevance focus used by the range planner. */\n\tquery: string;\n}\n\nexport interface LineRange {\n\t/** One-based inclusive first line. */\n\tstart: number;\n\t/** One-based inclusive last line. */\n\tend: number;\n}\n\nexport type RawLineEndpoint = number | string | boolean | null;\n\nexport interface RawLineRange {\n\tstart?: RawLineEndpoint;\n\tend?: RawLineEndpoint;\n}\n\nexport interface NumberedRegion {\n\treadonly __brand: \"NumberedRegion\";\n\tlines: string[];\n\theaderLineNumbers: ReadonlySet<number>;\n\tpriorMarkerNs: ReadonlyMap<number, number>;\n\t/** Optional future protected spans, expressed as one-based line numbers. */\n\tprotectedLineNumbers?: ReadonlySet<number>;\n\ttokenEstimate: number;\n}\n\nexport type ValidatedRanges = readonly LineRange[] & { readonly __brand: \"ValidatedRanges\" };\n\nexport interface CompactedTranscript {\n\ttext: string;\n\tranges: LineRange[];\n\t/**\n\t * Ranges force-preserved by `<keepContext>` protection; empty when nothing was protected.\n\t * Reported so protection that fired unexpectedly — a transcript that quotes tag text, say —\n\t * is diagnosable rather than a silent reduction in what compaction reclaimed.\n\t */\n\tkeptRanges: LineRange[];\n\tstats: VerbatimCompactionStats;\n}\n\nexport interface VerbatimCompactionStats {\n\tlinesBefore: number;\n\tlinesDeleted: number;\n\tlinesKept: number;\n\trangeCount: number;\n\ttokensBefore: number;\n\ttokensAfter: number;\n\tpercentReduction: number;\n}\n\n/** How much the caller can afford to lose if compaction does not happen. */\nexport type CompactionUrgency =\n\t/** Manual /compact, threshold auto-compaction — failing is safe. */\n\t| \"recoverable\"\n\t/** Overflow recovery, post-tool preflight — failing kills the turn. */\n\t| \"load_bearing\";\n\n/** How a durable compaction boundary was produced. */\nexport type CompactionRung = \"planned\" | \"extension\" | \"fresh\";\n\n/** Credentials for one planner request. Resolved per model, never shared. */\nexport interface PlannerAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * What one planner request may spend.\n *\n * `maxTokens` is declared `undefined`, not `number | undefined`: the type\n * forbids reintroducing the `0.8 * reserveTokens` output cap without changing\n * the type and failing review. pi-ai's `clampMaxTokensToContext` is the only bound.\n */\nexport interface PlannerBudget {\n\treadonly maxTokens: undefined;\n\treadonly reasoning: ThinkingLevel | undefined;\n}\n\n/**\n * A planner-only model borrowing. Cannot be confused with a session model switch.\n *\n * It carries no attempted-set key: the effective identity of an attempt is\n * `provider/model:<effective reasoning>`, derived from `model` and\n * `budget.reasoning` by `plannerAttemptKey`. Storing a key resolved from the raw\n * optional suffix would let the same effective request run twice.\n */\nexport interface BorrowedPlanner {\n\treadonly model: Model<Api>;\n\treadonly budget: PlannerBudget;\n\treadonly auth: PlannerAuth;\n}\n\n/** Identity of the model that ranked the deleted lines, when it was borrowed. */\nexport interface CompactionPlannerModel {\n\tprovider: string;\n\tid: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport interface VerbatimCompactionDetails {\n\tstrategy: typeof VERBATIM_COMPACTION_STRATEGY;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\tparameters: VerbatimCompactionParameters;\n\tstats: VerbatimCompactionStats;\n\trung: CompactionRung;\n\t/**\n\t * Authoritative whole-context count, projected for display only. Populated by\n\t * `createVerbatimCompactionMessage` on the rendered message; it is not\n\t * persisted here — the durable entry already carries it as\n\t * `CompactionEntry.tokensBefore`.\n\t */\n\ttokensBefore?: number;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\tbackupPath?: string;\n}\n\nexport interface VerbatimCompactionPreparation {\n\t/** First context-visible tail entry, or null when no pre-boundary message is retained. */\n\tfirstKeptEntryId: string | null;\n\tregion: NumberedRegion;\n\tregionEntryIds: string[];\n\tkeptTailMessageCount: number;\n\ttokensBefore: number;\n\tparameters: VerbatimCompactionParameters;\n\tsettings: CompactionSettings;\n}\n\nexport interface VerbatimCompactionResult {\n\tcompactedText: string;\n\tfirstKeptEntryId: string | null;\n\ttokensBefore: number;\n\tstats: VerbatimCompactionStats;\n\tparameters: VerbatimCompactionParameters;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\trung: CompactionRung;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** Aggregate usage across every planner request and retry in this compaction. */\n\tusage?: Usage;\n\tbackupPath?: string;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,YAAY,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/compaction/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,YAAY,CAAC","sourcesContent":["/**\n * Compaction support utilities.\n */\n\nexport * from \"./branch-summarization.ts\";\nexport * from \"./compaction.ts\";\nexport * from \"./compaction-boundary.js\";\nexport * from \"./compaction-parameters.js\";\nexport * from \"./compaction-runner.js\";\nexport * from \"./compaction-types.js\";\nexport * from \"./deleted-ranges.js\";\nexport * from \"./fallback-planner.js\";\nexport * from \"./planner-outcome.js\";\nexport * from \"./range-planner.js\";\nexport * from \"./range-planner-diagnostics.js\";\nexport * from \"./region-trimming.js\";\nexport * from \"./session-summarization.ts\";\nexport * from \"./transcript-serialization.js\";\nexport * from \"./utils.ts\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/compaction/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC","sourcesContent":["/**\n * Compaction support utilities.\n */\n\nexport * from \"./branch-summarization.ts\";\nexport * from \"./compaction.ts\";\nexport * from \"./compaction-boundary.js\";\nexport * from \"./compaction-parameters.js\";\nexport * from \"./compaction-runner.js\";\nexport * from \"./compaction-types.js\";\nexport * from \"./deleted-ranges.js\";\nexport * from \"./fallback-planner.js\";\nexport * from \"./planner-outcome.js\";\nexport * from \"./range-planner.js\";\nexport * from \"./range-planner-diagnostics.js\";\nexport * from \"./region-trimming.js\";\nexport * from \"./session-summarization.ts\";\nexport * from \"./transcript-serialization.js\";\nexport * from \"./utils.ts\";\nexport * from \"./whole-context-stats.js\";\n"]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { VerbatimCompactionStats } from "./compaction-types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Widen symmetric region-level compaction stats into whole-context stats using
|
|
4
|
+
* the independently estimated kept tail.
|
|
5
|
+
*
|
|
6
|
+
* Both before and after counts are deliberately heuristic and symmetric: the
|
|
7
|
+
* tail estimate is added to the heuristic region `tokensBefore` and — only when
|
|
8
|
+
* the tail is kept — to the heuristic region `tokensAfter`. `percentReduction`
|
|
9
|
+
* is recomputed from these two widened counts. The authoritative provider-aware
|
|
10
|
+
* `preparation.tokensBefore` is *never* mixed into this comparison; it travels
|
|
11
|
+
* separately (`VerbatimCompactionResult.tokensBefore` / `CompactionEntry.tokensBefore`)
|
|
12
|
+
* for budgeting and display only.
|
|
13
|
+
*
|
|
14
|
+
* A dropped tail contributes to the heuristic before count but not the after
|
|
15
|
+
* count, which is what makes fresh-compaction stats honest about the content
|
|
16
|
+
* actually being dropped.
|
|
17
|
+
*
|
|
18
|
+
* Shared by the planned, fresh, and extension compaction rungs (#2052).
|
|
19
|
+
*/
|
|
20
|
+
export declare function widenToWholeContextStats(regionStats: VerbatimCompactionStats, keptTailEstimate: number, keptTail: boolean): VerbatimCompactionStats;
|
|
21
|
+
//# sourceMappingURL=whole-context-stats.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"whole-context-stats.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/whole-context-stats.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAMrE;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,wBAAwB,CACvC,WAAW,EAAE,uBAAuB,EACpC,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,OAAO,GACf,uBAAuB,CASzB"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
function computePercentReduction(tokensBefore, tokensAfter) {
|
|
2
|
+
return tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / tokensBefore) * 1000) / 10;
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Widen symmetric region-level compaction stats into whole-context stats using
|
|
6
|
+
* the independently estimated kept tail.
|
|
7
|
+
*
|
|
8
|
+
* Both before and after counts are deliberately heuristic and symmetric: the
|
|
9
|
+
* tail estimate is added to the heuristic region `tokensBefore` and — only when
|
|
10
|
+
* the tail is kept — to the heuristic region `tokensAfter`. `percentReduction`
|
|
11
|
+
* is recomputed from these two widened counts. The authoritative provider-aware
|
|
12
|
+
* `preparation.tokensBefore` is *never* mixed into this comparison; it travels
|
|
13
|
+
* separately (`VerbatimCompactionResult.tokensBefore` / `CompactionEntry.tokensBefore`)
|
|
14
|
+
* for budgeting and display only.
|
|
15
|
+
*
|
|
16
|
+
* A dropped tail contributes to the heuristic before count but not the after
|
|
17
|
+
* count, which is what makes fresh-compaction stats honest about the content
|
|
18
|
+
* actually being dropped.
|
|
19
|
+
*
|
|
20
|
+
* Shared by the planned, fresh, and extension compaction rungs (#2052).
|
|
21
|
+
*/
|
|
22
|
+
export function widenToWholeContextStats(regionStats, keptTailEstimate, keptTail) {
|
|
23
|
+
const tokensBefore = regionStats.tokensBefore + keptTailEstimate;
|
|
24
|
+
const tokensAfter = regionStats.tokensAfter + (keptTail ? keptTailEstimate : 0);
|
|
25
|
+
return {
|
|
26
|
+
...regionStats,
|
|
27
|
+
tokensBefore,
|
|
28
|
+
tokensAfter,
|
|
29
|
+
percentReduction: computePercentReduction(tokensBefore, tokensAfter),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=whole-context-stats.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"whole-context-stats.js","sourceRoot":"","sources":["../../../src/core/compaction/whole-context-stats.ts"],"names":[],"mappings":"AAEA,SAAS,uBAAuB,CAAC,YAAoB,EAAE,WAAmB;IACzE,OAAO,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,YAAY,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;AAC1F,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,wBAAwB,CACvC,WAAoC,EACpC,gBAAwB,EACxB,QAAiB;IAEjB,MAAM,YAAY,GAAG,WAAW,CAAC,YAAY,GAAG,gBAAgB,CAAC;IACjE,MAAM,WAAW,GAAG,WAAW,CAAC,WAAW,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChF,OAAO;QACN,GAAG,WAAW;QACd,YAAY;QACZ,WAAW;QACX,gBAAgB,EAAE,uBAAuB,CAAC,YAAY,EAAE,WAAW,CAAC;KACpE,CAAC;AACH,CAAC","sourcesContent":["import type { VerbatimCompactionStats } from \"./compaction-types.js\";\n\nfunction computePercentReduction(tokensBefore: number, tokensAfter: number): number {\n\treturn tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / tokensBefore) * 1000) / 10;\n}\n\n/**\n * Widen symmetric region-level compaction stats into whole-context stats using\n * the independently estimated kept tail.\n *\n * Both before and after counts are deliberately heuristic and symmetric: the\n * tail estimate is added to the heuristic region `tokensBefore` and — only when\n * the tail is kept — to the heuristic region `tokensAfter`. `percentReduction`\n * is recomputed from these two widened counts. The authoritative provider-aware\n * `preparation.tokensBefore` is *never* mixed into this comparison; it travels\n * separately (`VerbatimCompactionResult.tokensBefore` / `CompactionEntry.tokensBefore`)\n * for budgeting and display only.\n *\n * A dropped tail contributes to the heuristic before count but not the after\n * count, which is what makes fresh-compaction stats honest about the content\n * actually being dropped.\n *\n * Shared by the planned, fresh, and extension compaction rungs (#2052).\n */\nexport function widenToWholeContextStats(\n\tregionStats: VerbatimCompactionStats,\n\tkeptTailEstimate: number,\n\tkeptTail: boolean,\n): VerbatimCompactionStats {\n\tconst tokensBefore = regionStats.tokensBefore + keptTailEstimate;\n\tconst tokensAfter = regionStats.tokensAfter + (keptTail ? keptTailEstimate : 0);\n\treturn {\n\t\t...regionStats,\n\t\ttokensBefore,\n\t\ttokensAfter,\n\t\tpercentReduction: computePercentReduction(tokensBefore, tokensAfter),\n\t};\n}\n"]}
|
|
@@ -12,7 +12,7 @@ export { decideReactiveWidgetAction, installReactiveWidget, } from "./reactive-w
|
|
|
12
12
|
export type { ExtensionErrorListener, ForkHandler, NavigateTreeHandler, NewSessionHandler, ShutdownHandler, SwitchSessionHandler, } from "./runner.ts";
|
|
13
13
|
export { ExtensionRunner } from "./runner.ts";
|
|
14
14
|
export { isStaleExtensionContextError, STALE_EXTENSION_CONTEXT_MARKER } from "./stale-context.ts";
|
|
15
|
-
export type { AfterProviderResponseEvent, AgentEndEvent, AgentSettledEvent, AgentStartEvent, AgentToolResult, AgentToolUpdateCallback, AppendEntryHandler, AppKeybinding, AutocompleteProviderFactory, BashToolCallEvent, BashToolResultEvent, BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, BeforeProviderRequestEventResult, BuildSystemPromptOptions, CompactOptions, ContextEvent, ContextEventResult, ContextUsage, CustomMessageDelivery, CustomToolCallEvent, CustomToolResultEvent, EditorFactory, EditToolCallEvent, EditToolResultEvent, EntryRenderer, EntryRenderOptions, ExecOptions, ExecResult, Extension, ExtensionActions, ExtensionAPI, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionCustomComponent, ExtensionError, ExtensionEvent, ExtensionFactory, ExtensionFlag, ExtensionHandler, ExtensionMode, ExtensionRuntime, ExtensionScopedModels, ExtensionShortcut, ExtensionUIContext, ExtensionUIDialogOptions, ExtensionWidgetOptions, FindToolCallEvent, FindToolResultEvent, GetActiveToolsHandler, GetAllToolsHandler, GetCommandsHandler, GetThinkingLevelHandler, HostCustomUiState, HostCustomUiStateListener, HostInputFormField, HostInputFormFieldType, HostInputFormRequest, HostSessionPickerHandle, HostSessionPickerRequest, HostSessionPickerRow, InlineExtension, InputEvent, InputEventResult, InputSource, KeybindingsManager, LoadExtensionsResult, LsToolCallEvent, LsToolResultEvent, MarkdownTransformContext, MarkdownTransformer, MessageEndEvent, MessageRenderer, MessageRenderOptions, MessageStartEvent, MessageUpdateEvent, ModelSelectEvent, ModelSelectSource, OrchestrationContext, PowerShellToolCallEvent, PowerShellToolResultEvent, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventDecision, ProjectTrustEventResult, ProjectTrustHandler, ProviderConfig, ProviderModelConfig, ReadToolCallEvent, ReadToolResultEvent, RegisteredCommand, RegisteredTool, ReplacedSessionContext, ResolvedCommand, ResourcesDiscoverEvent, ResourcesDiscoverResult, ScopedModel, ScrollableWidgetComponent, SendMessageHandler, SendMessageOptions, SendMessagesHandler, SendMessagesOptions, SendUserMessageHandler, SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionBeforeForkEvent, SessionBeforeForkResult, SessionBeforeSwitchEvent, SessionBeforeSwitchResult, SessionBeforeTreeEvent, SessionBeforeTreeResult, SessionCompactEvent, SessionCompactFailedEvent, SessionEvent, SessionInfoChangedEvent, SessionShutdownEvent, SessionStartEvent, SessionTreeEvent, SetActiveToolsHandler, SetLabelHandler, SetModelHandler, SetThinkingLevelHandler, SubagentChildPolicy, SubagentIntercomIdentity, TerminalInputHandler, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionMode, ToolExecutionStartEvent, ToolExecutionUpdateEvent, ToolInfo, ToolRenderResultOptions, ToolResultEvent, ToolResultEventResult, TreePreparation, TurnEndEvent, TurnStartEvent, UIPromptEndEvent, UIPromptKind, UIPromptStartEvent, UserBashEvent, UserBashEventResult, WidgetPlacement, WidgetScrollRequest, WidgetScrollState, WorkflowPendingStageDelivery, WorkflowPendingStageMessage, WorkflowPendingStageSender, WorkflowStageOrchestrationContext, WorkingIndicatorOptions, WriteToolCallEvent, WriteToolResultEvent, } from "./types.ts";
|
|
15
|
+
export type { AfterProviderResponseEvent, AgentEndEvent, AgentSettledEvent, AgentStartEvent, AgentToolResult, AgentToolUpdateCallback, AppendEntryHandler, AppKeybinding, AutocompleteProviderFactory, BashToolCallEvent, BashToolResultEvent, BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, BeforeProviderRequestEventResult, BuildSystemPromptOptions, CompactOptions, ContextEvent, ContextEventResult, ContextUsage, CustomMessageDelivery, CustomToolCallEvent, CustomToolResultEvent, EditorFactory, EditToolCallEvent, EditToolResultEvent, EntryRenderer, EntryRenderOptions, ExecOptions, ExecResult, Extension, ExtensionActions, ExtensionAPI, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionCustomComponent, ExtensionError, ExtensionEvent, ExtensionFactory, ExtensionFlag, ExtensionHandler, ExtensionMode, ExtensionRuntime, ExtensionScopedModels, ExtensionShortcut, ExtensionUIContext, ExtensionUIDialogOptions, ExtensionWidgetOptions, FindToolCallEvent, FindToolResultEvent, GetActiveToolsHandler, GetAllToolsHandler, GetCommandsHandler, GetThinkingLevelHandler, HostCustomUiState, HostCustomUiStateListener, HostInputFormField, HostInputFormFieldType, HostInputFormRequest, HostSessionPickerHandle, HostSessionPickerRequest, HostSessionPickerRow, InlineExtension, InputEvent, InputEventResult, InputSource, KeybindingsManager, LoadExtensionsResult, LsToolCallEvent, LsToolResultEvent, MarkdownTransformContext, MarkdownTransformer, MessageEndEvent, MessageEndEventResult, MessageRenderer, MessageRenderOptions, MessageStartEvent, MessageUpdateEvent, ModelSelectEvent, ModelSelectSource, OrchestrationContext, PowerShellToolCallEvent, PowerShellToolResultEvent, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventDecision, ProjectTrustEventResult, ProjectTrustHandler, ProviderConfig, ProviderModelConfig, ReadToolCallEvent, ReadToolResultEvent, RegisteredCommand, RegisteredTool, ReplacedSessionContext, ResolvedCommand, ResourcesDiscoverEvent, ResourcesDiscoverResult, ScopedModel, ScrollableWidgetComponent, SendMessageHandler, SendMessageOptions, SendMessagesHandler, SendMessagesOptions, SendUserMessageHandler, SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionBeforeForkEvent, SessionBeforeForkResult, SessionBeforeSwitchEvent, SessionBeforeSwitchResult, SessionBeforeTreeEvent, SessionBeforeTreeResult, SessionCompactEvent, SessionCompactFailedEvent, SessionEvent, SessionInfoChangedEvent, SessionShutdownEvent, SessionStartEvent, SessionTreeEvent, SetActiveToolsHandler, SetLabelHandler, SetModelHandler, SetThinkingLevelHandler, SubagentChildPolicy, SubagentIntercomIdentity, TerminalInputHandler, ThinkingLevelSelectEvent, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionMode, ToolExecutionStartEvent, ToolExecutionUpdateEvent, ToolInfo, ToolRenderResultOptions, ToolResultEvent, ToolResultEventResult, TreePreparation, TurnEndEvent, TurnStartEvent, UIPromptEndEvent, UIPromptKind, UIPromptStartEvent, UserBashEvent, UserBashEventResult, WidgetPlacement, WidgetScrollRequest, WidgetScrollState, WorkflowPendingStageDelivery, WorkflowPendingStageMessage, WorkflowPendingStageSender, WorkflowStageOrchestrationContext, WorkingIndicatorOptions, WriteToolCallEvent, WriteToolResultEvent, } from "./types.ts";
|
|
16
16
|
export { defineTool, isBashToolResult, isEditToolResult, isFindToolResult, isLsToolResult, isPowerShellToolResult, isReadToolResult, isSearchToolResult, isToolCallEventType, isWriteToolResult, } from "./types.ts";
|
|
17
17
|
export { OVERLAY_ACTIVE_ROW_MARKER } from "./ui-types.ts";
|
|
18
18
|
export type * from "./workflow-events.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,YAAY,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AACvE,YAAY,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AACrE,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACjF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,EACvB,mBAAmB,EACnB,wBAAwB,EACxB,oBAAoB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,YAAY,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AACvE,YAAY,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AACrE,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACjF,YAAY,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,YAAY,EAAE,wBAAwB,EAAE,6BAA6B,EAAE,MAAM,aAAa,CAAC;AAC3F,OAAO,EACN,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,cAAc,GACd,MAAM,aAAa,CAAC;AACrB,YAAY,EACX,4BAA4B,EAC5B,oBAAoB,EACpB,uBAAuB,EACvB,wBAAwB,EACxB,qBAAqB,EACrB,2BAA2B,EAC3B,2BAA2B,EAC3B,yBAAyB,EACzB,uBAAuB,EACvB,sBAAsB,EACtB,yBAAyB,EACzB,gBAAgB,GAChB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACN,0BAA0B,EAC1B,qBAAqB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACX,sBAAsB,EACtB,WAAW,EACX,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,oBAAoB,GACpB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,4BAA4B,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AAClG,YAAY,EACX,0BAA0B,EAC1B,aAAa,EACb,iBAAiB,EACjB,eAAe,EAEf,eAAe,EACf,uBAAuB,EACvB,kBAAkB,EAElB,aAAa,EACb,2BAA2B,EAE3B,iBAAiB,EACjB,mBAAmB,EACnB,qBAAqB,EACrB,2BAA2B,EAC3B,0B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