@agimon-ai/po-autocompact 0.0.0-alpha.41 → 0.0.0-alpha.43
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/dist/{compactionPolicy-_WTvdEQ2.mjs → compactionPolicy-C0s8QH4P.mjs} +4 -3
- package/dist/compactionPolicy-C0s8QH4P.mjs.map +1 -0
- package/dist/{compactionPolicy-C76UDULA.cjs → compactionPolicy-CgYnxg8c.cjs} +4 -3
- package/dist/{compactionPolicy-_WTvdEQ2.mjs.map → compactionPolicy-CgYnxg8c.cjs.map} +1 -1
- package/dist/extensions/server.cjs +42 -33
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.mjs +42 -33
- package/dist/extensions/server.mjs.map +1 -1
- package/dist/extensions/web.mjs +9 -2
- package/dist/extensions/web.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +8 -7
- package/dist/compactionPolicy-C76UDULA.cjs.map +0 -1
|
@@ -303,9 +303,10 @@ function mergeFileDetails(current, fileOps, additional) {
|
|
|
303
303
|
...fileOps ? [...fileOps.read] : []
|
|
304
304
|
]);
|
|
305
305
|
for (const path of modified) read.delete(path);
|
|
306
|
+
const recent = (paths) => [...paths].slice(-500).sort();
|
|
306
307
|
return {
|
|
307
|
-
readFiles:
|
|
308
|
-
modifiedFiles:
|
|
308
|
+
readFiles: recent(read),
|
|
309
|
+
modifiedFiles: recent(modified)
|
|
309
310
|
};
|
|
310
311
|
}
|
|
311
312
|
function fileDetailsFromUnknown(value) {
|
|
@@ -325,4 +326,4 @@ function withCanonicalFileSections(summary, details) {
|
|
|
325
326
|
//#endregion
|
|
326
327
|
export { STATE_CUSTOM_TYPE as C, RUNTIME_STATE_MESSAGE_TYPE as S, thresholdTokens as _, createInitialState as a, CONTEXT_MESSAGE_TYPE as b, effectiveThresholds as c, isStructuredCheckpoint as d, latestCheckpointArtifactEntry as f, projectContextMessages as g, parseState as h, contextDetailsFromUnknown as i, fileDetailsFromUnknown as l, parseCheckpointDecision as m, checkpointRequestDetails as n, createRequestId as o, mergeFileDetails as p, checkpointSummaryFromEntry as r, customMessage as s, baselineUsageIsSettled as t, fileOperationsFromMessages as u, withCanonicalFileSections as v, RESUME_MESSAGE_TYPE as x, CHECKPOINT_MESSAGE_TYPE as y };
|
|
327
328
|
|
|
328
|
-
//# sourceMappingURL=compactionPolicy-
|
|
329
|
+
//# sourceMappingURL=compactionPolicy-C0s8QH4P.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compactionPolicy-C0s8QH4P.mjs","names":[],"sources":["../src/constants/autocompact.ts","../src/services/compactionPolicy/index.ts"],"sourcesContent":["export const STATE_CUSTOM_TYPE = 'po-autocompact-state';\nexport const CHECKPOINT_MESSAGE_TYPE = 'po-autocompact-checkpoint';\nexport const CONTEXT_MESSAGE_TYPE = 'po-autocompact-context';\nexport const RESUME_MESSAGE_TYPE = 'po-autocompact-resume';\nexport const RUNTIME_STATE_MESSAGE_TYPE = 'po-autocompact-runtime-state';\nexport const STATE_VERSION = 2;\n/** Retrying a malformed checkpoint costs a full summarization call per turn, so a pass that\n * keeps failing is abandoned instead of retried for the rest of the session. */\nexport const MAX_INVALID_CHECKPOINT_ATTEMPTS = 3;\n\nexport const COMPACTION_THRESHOLDS = {\n 1: { ratio: 0.5, capTokens: 200_000 },\n 2: { ratio: 0.75, capTokens: 500_000 },\n 3: { ratio: 0.95, capTokens: 800_000 },\n} as const;\n\nexport const CHECKPOINT_HEADINGS = [\n '## Goal',\n '## Constraints & Preferences',\n '## Progress',\n '### Done',\n '### In Progress',\n '### Blocked',\n '## Key Decisions',\n '## Next Steps',\n '## Critical Context',\n] as const;\n","import {\n DEFAULT_COMPACTION_SETTINGS,\n type FileOperations,\n type SessionEntry,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\n\nimport {\n CHECKPOINT_HEADINGS,\n CHECKPOINT_MESSAGE_TYPE,\n COMPACTION_THRESHOLDS,\n CONTEXT_MESSAGE_TYPE,\n STATE_VERSION,\n} from '../../constants/autocompact';\nimport type {\n AutocompactContextDetails,\n AutocompactFileDetails,\n AutocompactRatioOverrides,\n AutocompactTokenOverrides,\n AutocompactMessage,\n AutocompactPass,\n AutocompactState,\n CheckpointDecision,\n CheckpointRequestDetails,\n ContextProjection,\n} from '../../types/autocompact';\n\n/** V4 projections have numeric timestamps and store custom messages as message entries. */\nexport type NativePolicyEntry = { id: string; timestamp: number } & (\n | { type: 'message'; message: AutocompactMessage }\n | { type: 'custom'; customType: string; data?: unknown }\n | { type: 'compaction'; summary: string; tokensBefore: number; retainedTail: AutocompactMessage[] }\n | { type: 'branch_summary'; summary: string; fromId?: string | null }\n);\nexport type CompactionPolicyEntry = SessionEntry | NativePolicyEntry;\n\nexport function customMessage(\n entry: CompactionPolicyEntry,\n): Extract<SessionEntry, { type: 'custom_message' }> | Extract<AutocompactMessage, { role: 'custom' }> | undefined {\n if (entry.type === 'custom_message') return entry;\n if (entry.type === 'message' && entry.message.role === 'custom') return entry.message;\n return undefined;\n}\n\n/** Native entries are already projected messages, not Pi journal entries. */\nexport function policyEntryMessages(entry: CompactionPolicyEntry): AutocompactMessage[] {\n if (typeof entry.timestamp === 'string') return sessionEntryToContextMessages(entry as SessionEntry);\n if (entry.type === 'message') return [entry.message];\n if (entry.type === 'compaction' && 'retainedTail' in entry) {\n return [\n {\n role: 'compactionSummary',\n summary: entry.summary,\n tokensBefore: entry.tokensBefore,\n timestamp: entry.timestamp,\n },\n ...entry.retainedTail,\n ];\n }\n if (entry.type === 'branch_summary') {\n return [{ role: 'branchSummary', summary: entry.summary, fromId: entry.fromId ?? '', timestamp: entry.timestamp }];\n }\n return [];\n}\n\nconst SHOULD_COMPACT_PATTERN = /<shouldCompact>\\s*(true|false)\\s*<\\/shouldCompact>/i;\nconst FILE_SECTION_PATTERN = /\\n*<(?:read-files|modified-files)>[\\s\\S]*?<\\/(?:read-files|modified-files)>/g;\n// ponytail: the most recently touched paths per list; older ones fall out of state and summaries.\n// Raise it, or move file history to the artifact mirror, if long sessions need the full list.\nconst MAX_FILE_DETAILS = 500;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === 'string');\n}\n\nfunction isPass(value: unknown): value is AutocompactPass {\n return value === 1 || value === 2 || value === 3;\n}\n\nfunction assistantText(entry: CompactionPolicyEntry): string | undefined {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return undefined;\n const text = entry.message.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n')\n .trim();\n return text || undefined;\n}\n\nfunction isAutocompactMessage(value: unknown): value is AutocompactMessage {\n return isRecord(value) && typeof value.role === 'string';\n}\n\nexport function contextDetailsFromUnknown(value: unknown): AutocompactContextDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (!Array.isArray(value.retainedMessages) || !value.retainedMessages.every(isAutocompactMessage)) return undefined;\n if (!isRecord(value.poAutocompact)) return undefined;\n const marker = value.poAutocompact;\n if (\n marker.version !== STATE_VERSION ||\n (marker.pass !== 2 && marker.pass !== 3) ||\n typeof marker.cycle !== 'number' ||\n typeof marker.requestId !== 'string' ||\n typeof marker.snapshotLeafId !== 'string' ||\n typeof marker.tokensBefore !== 'number'\n )\n return undefined;\n return {\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n retainedMessages: [...value.retainedMessages],\n poAutocompact: {\n version: STATE_VERSION,\n cycle: marker.cycle,\n pass: marker.pass,\n requestId: marker.requestId,\n snapshotLeafId: marker.snapshotLeafId,\n tokensBefore: marker.tokensBefore,\n },\n };\n}\n\nexport function createInitialState(): AutocompactState {\n return {\n version: STATE_VERSION,\n cycle: 1,\n pass: 1,\n phase: 'waiting',\n checkpointQueue: [],\n exhaustedPasses: [],\n invalidAttempts: 0,\n baselineTokens: 0,\n baselinePending: false,\n readFiles: [],\n modifiedFiles: [],\n };\n}\n\n/**\n * The ratios each pass fires at, with configured values folded in.\n *\n * The ladder only works if it climbs, so a configured pass never sits below the\n * one before it: a file that says pass 2 fires earlier than pass 1 gets pass 1's\n * ratio for pass 2 rather than a pass that can never contribute.\n */\nexport function compactionRatios(configured: AutocompactRatioOverrides = {}): Record<AutocompactPass, number> {\n let previous = 0;\n const ratios = {} as Record<AutocompactPass, number>;\n for (const pass of [1, 2, 3] as const) {\n const ratio = Math.max(configured[pass] ?? COMPACTION_THRESHOLDS[pass].ratio, previous);\n ratios[pass] = ratio;\n previous = ratio;\n }\n return ratios;\n}\n\nexport function thresholdTokens(\n pass: AutocompactPass,\n contextWindow: number,\n baselineTokens = 0,\n configured: AutocompactRatioOverrides = {},\n): number {\n const threshold = COMPACTION_THRESHOLDS[pass];\n const ratio = compactionRatios(configured)[pass];\n const baseline = Math.max(0, Math.min(baselineTokens, contextWindow));\n const remaining = contextWindow - baseline;\n const staged = baseline + Math.min(Math.floor(remaining * ratio), threshold.capTokens);\n // Pi compacts natively above `contextWindow - reserveTokens`. A staged threshold above that\n // point can never fire, so the ladder would silently degrade into native compaction: on a\n // 200k window the raw pass 3 ratio lands at 190_000, while Pi already compacted at 183_616.\n const nativeTrigger = contextWindow - DEFAULT_COMPACTION_SETTINGS.reserveTokens;\n return nativeTrigger > baseline ? Math.min(staged, nativeTrigger) : staged;\n}\n\n/**\n * Where every pass fires, with a matching model's absolute token checkpoints folded in.\n *\n * A configured token count replaces the ratio only when it fires earlier, so an\n * override can bring a checkpoint forward on a very large window without ever\n * pushing one past the point Pi compacts natively.\n *\n * Two rules keep the ladder usable. A token count at or below the baseline is\n * ignored, because a compaction that lands above it would otherwise satisfy that\n * pass the moment the next cycle opens and re-fire it every turn. And a pass never\n * sits below the one before it, for the same reason {@link compactionRatios}\n * climbs: `evaluateUsage` skips any pass below the one already reached, so a later\n * pass that fires first does not merely reorder the ladder, it locks the earlier\n * passes out of the cycle and forces compaction with no summary ever written.\n */\nexport function effectiveThresholds(\n contextWindow: number,\n baselineTokens = 0,\n configured: AutocompactRatioOverrides = {},\n tokenOverrides: AutocompactTokenOverrides = {},\n): Record<AutocompactPass, number> {\n let previous = 0;\n const thresholds = {} as Record<AutocompactPass, number>;\n for (const pass of [1, 2, 3] as const) {\n const ratioTokens = thresholdTokens(pass, contextWindow, baselineTokens, configured);\n const absolute = tokenOverrides[pass];\n const staged = absolute !== undefined && absolute > baselineTokens ? Math.min(ratioTokens, absolute) : ratioTokens;\n thresholds[pass] = Math.max(staged, previous);\n previous = thresholds[pass];\n }\n return thresholds;\n}\nexport function latestCheckpointArtifactEntry(\n branchEntries: readonly CompactionPolicyEntry[],\n): CompactionPolicyEntry | undefined {\n return branchEntries.findLast(\n (entry) =>\n entry.type === 'compaction' ||\n // Staged checkpoints are plain entries so they stay out of the agent's LLM context.\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n // Legacy sessions staged checkpoints as custom messages; committed markers still are.\n customMessage(entry)?.customType === CHECKPOINT_MESSAGE_TYPE ||\n customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE,\n );\n}\n\nexport function baselineUsageIsSettled(branchEntries: readonly CompactionPolicyEntry[]): boolean {\n const boundaryIndex = branchEntries.findLastIndex(\n (entry) => entry.type === 'compaction' || customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE,\n );\n return branchEntries.slice(boundaryIndex + 1).some((entry) => {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return false;\n const { stopReason, usage } = entry.message;\n if (stopReason === 'aborted' || stopReason === 'error' || !usage) return false;\n return (usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;\n });\n}\n\nexport function retainedMessagesAfterSnapshot(\n branchEntries: readonly CompactionPolicyEntry[],\n snapshotLeafId: string,\n): AutocompactMessage[] {\n const snapshotIndex = branchEntries.findIndex((entry) => entry.id === snapshotLeafId);\n if (snapshotIndex === -1) return [];\n return branchEntries\n .slice(snapshotIndex + 1)\n .filter((entry) => customMessage(entry)?.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap(policyEntryMessages);\n}\n\nexport function projectContextMessages(\n messages: AutocompactMessage[],\n branchEntries: readonly CompactionPolicyEntry[],\n): ContextProjection {\n const nativeCompactionIndex = branchEntries.findLastIndex((entry) => entry.type === 'compaction');\n const markerEntry = branchEntries\n .slice(nativeCompactionIndex + 1)\n .findLast((entry) => customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE);\n const markerMessage = markerEntry && customMessage(markerEntry);\n if (!markerEntry || !markerMessage) {\n return { messages, retainedMessageCount: 0 };\n }\n\n const details = contextDetailsFromUnknown(markerMessage.details);\n const summary = checkpointSummaryFromEntry(markerEntry);\n if (!details || !summary) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const markerMessageIndex = messages.findLastIndex(\n (message) =>\n message.role === 'custom' &&\n message.customType === CONTEXT_MESSAGE_TYPE &&\n contextDetailsFromUnknown(message.details)?.poAutocompact.requestId === details.poAutocompact.requestId,\n );\n if (markerMessageIndex === -1) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const summaryMessage: AutocompactMessage = {\n role: 'compactionSummary',\n summary,\n tokensBefore: details.poAutocompact.tokensBefore,\n timestamp: messages[markerMessageIndex]?.timestamp ?? Date.now(),\n };\n return {\n messages: [summaryMessage, ...details.retainedMessages, ...messages.slice(markerMessageIndex + 1)],\n marker: details.poAutocompact,\n retainedMessageCount: details.retainedMessages.length,\n };\n}\n\nexport function fileOperationsFromMessages(messages: AutocompactMessage[]): FileOperations {\n const fileOps: FileOperations = { read: new Set(), written: new Set(), edited: new Set() };\n for (const message of messages) {\n if (message.role !== 'assistant') continue;\n for (const block of message.content) {\n if (block.type !== 'toolCall') continue;\n const path = typeof block.arguments.path === 'string' ? block.arguments.path : undefined;\n if (!path) continue;\n if (block.name === 'read') fileOps.read.add(path);\n else if (block.name === 'write') fileOps.written.add(path);\n else if (block.name === 'edit') fileOps.edited.add(path);\n }\n }\n return fileOps;\n}\n\nexport function parseState(value: unknown): AutocompactState | undefined {\n if (!isRecord(value)) return undefined;\n if (value.version !== STATE_VERSION || typeof value.cycle !== 'number' || !isPass(value.pass)) return undefined;\n if (\n value.phase !== 'waiting' &&\n value.phase !== 'checkpoint_pending' &&\n value.phase !== 'checkpoint_ready' &&\n value.phase !== 'compacting'\n )\n return undefined;\n const baselineTokens = value.baselineTokens ?? 0;\n if (typeof baselineTokens !== 'number' || baselineTokens < 0) return undefined;\n const baselinePending = value.baselinePending ?? false;\n if (typeof baselinePending !== 'boolean') return undefined;\n const checkpointQueue = value.checkpointQueue ?? [];\n if (\n !Array.isArray(checkpointQueue) ||\n !checkpointQueue.every(isPass) ||\n checkpointQueue.some((pass, index) => index > 0 && pass <= checkpointQueue[index - 1]!)\n )\n return undefined;\n // Sessions persisted before bounded retry landed simply have no attempt history to restore.\n const exhaustedPasses = value.exhaustedPasses ?? [];\n if (!Array.isArray(exhaustedPasses) || !exhaustedPasses.every(isPass)) return undefined;\n const invalidAttempts = value.invalidAttempts ?? 0;\n if (typeof invalidAttempts !== 'number' || invalidAttempts < 0) return undefined;\n if (!isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (value.requestId !== undefined && typeof value.requestId !== 'string') return undefined;\n if (value.compactionPass !== undefined && value.compactionPass !== 2 && value.compactionPass !== 3) return undefined;\n if ('latestCheckpointEntryId' in value) return undefined;\n if (value.latestCheckpointSnapshotLeafId !== undefined && typeof value.latestCheckpointSnapshotLeafId !== 'string')\n return undefined;\n if (value.lastAttemptLeafId !== undefined && typeof value.lastAttemptLeafId !== 'string') return undefined;\n if (value.snapshotLeafId !== undefined && typeof value.snapshotLeafId !== 'string') return undefined;\n if (value.snapshotTokens !== undefined && (typeof value.snapshotTokens !== 'number' || value.snapshotTokens < 0))\n return undefined;\n if (value.pendingCheckpoint !== undefined && typeof value.pendingCheckpoint !== 'string') return undefined;\n\n return {\n version: STATE_VERSION,\n cycle: value.cycle,\n pass: value.pass,\n phase: value.phase,\n checkpointQueue: [...checkpointQueue],\n exhaustedPasses: [...exhaustedPasses],\n invalidAttempts,\n baselineTokens,\n baselinePending,\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n ...(value.requestId ? { requestId: value.requestId } : {}),\n ...(value.compactionPass ? { compactionPass: value.compactionPass } : {}),\n ...(value.latestCheckpointSnapshotLeafId\n ? { latestCheckpointSnapshotLeafId: value.latestCheckpointSnapshotLeafId }\n : {}),\n ...(value.lastAttemptLeafId ? { lastAttemptLeafId: value.lastAttemptLeafId } : {}),\n ...(value.snapshotLeafId ? { snapshotLeafId: value.snapshotLeafId } : {}),\n ...(value.snapshotTokens !== undefined ? { snapshotTokens: value.snapshotTokens } : {}),\n ...(value.pendingCheckpoint ? { pendingCheckpoint: value.pendingCheckpoint } : {}),\n };\n}\n\nexport function checkpointSummaryFromEntry(entry: CompactionPolicyEntry | undefined): string | undefined {\n if (!entry) return undefined;\n if (entry.type === 'compaction') return entry.summary.trim() || undefined;\n if (entry.type === 'custom') {\n return isRecord(entry.data) && typeof entry.data.summary === 'string'\n ? entry.data.summary.trim() || undefined\n : undefined;\n }\n const marker = customMessage(entry);\n if (marker) {\n const content =\n typeof marker.content === 'string'\n ? marker.content\n : marker.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n return content.trim() || undefined;\n }\n return assistantText(entry);\n}\n\nexport function parseCheckpointDecision(response: string): CheckpointDecision {\n const match = response.match(SHOULD_COMPACT_PATTERN);\n const summary = response.replace(SHOULD_COMPACT_PATTERN, '').trim();\n if (!match) return { summary };\n return { summary, shouldCompact: match[1]?.toLowerCase() === 'true' };\n}\n\nexport function isStructuredCheckpoint(summary: string): boolean {\n return CHECKPOINT_HEADINGS.every((heading) => summary.includes(heading));\n}\n\nexport function createRequestId(\n sessionId: string,\n cycle: number,\n pass: AutocompactPass,\n leafId: string | null,\n): string {\n return `${sessionId}:${cycle}:${pass}:${leafId ?? 'root'}`;\n}\n\nexport function checkpointRequestDetails(\n cycle: number,\n pass: AutocompactPass,\n requestId: string,\n): CheckpointRequestDetails {\n return { version: STATE_VERSION, cycle, pass, requestId };\n}\n\nexport function mergeFileDetails(\n current: AutocompactFileDetails,\n fileOps?: FileOperations,\n additional?: AutocompactFileDetails,\n): AutocompactFileDetails {\n const modified = new Set([\n ...current.modifiedFiles,\n ...(additional?.modifiedFiles ?? []),\n ...(fileOps ? [...fileOps.edited, ...fileOps.written] : []),\n ]);\n const read = new Set([...current.readFiles, ...(additional?.readFiles ?? []), ...(fileOps ? [...fileOps.read] : [])]);\n for (const path of modified) read.delete(path);\n // Sets keep insertion order, so the tail holds the newest paths.\n const recent = (paths: Set<string>) => [...paths].slice(-MAX_FILE_DETAILS).sort();\n return { readFiles: recent(read), modifiedFiles: recent(modified) };\n}\n\nexport function fileDetailsFromUnknown(value: unknown): AutocompactFileDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n return { readFiles: value.readFiles, modifiedFiles: value.modifiedFiles };\n}\n\nexport function withCanonicalFileSections(summary: string, details: AutocompactFileDetails): string {\n const sections: string[] = [];\n if (details.readFiles.length > 0) sections.push(`<read-files>\\n${details.readFiles.join('\\n')}\\n</read-files>`);\n if (details.modifiedFiles.length > 0) {\n sections.push(`<modified-files>\\n${details.modifiedFiles.join('\\n')}\\n</modified-files>`);\n }\n const normalized = summary.replace(FILE_SECTION_PATTERN, '').trim();\n return sections.length > 0 ? `${normalized}\\n\\n${sections.join('\\n\\n')}` : normalized;\n}\n"],"mappings":";;AAAA,MAAa,oBAAoB;AACjC,MAAa,0BAA0B;AACvC,MAAa,uBAAuB;AACpC,MAAa,sBAAsB;AACnC,MAAa,6BAA6B;AAM1C,MAAa,wBAAwB;CACnC,GAAG;EAAE,OAAO;EAAK,WAAW;C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IAAI,CAAC;CAC3D,CAAC;CACD,MAAM,uBAAO,IAAI,IAAI;EAAC,GAAG,QAAQ;EAAW,GAAI,YAAY,aAAa,CAAC;EAAI,GAAI,UAAU,CAAC,GAAG,QAAQ,IAAI,IAAI,CAAC;CAAE,CAAC;CACpH,KAAK,MAAM,QAAQ,UAAU,KAAK,OAAO,IAAI;CAE7C,MAAM,UAAU,UAAuB,CAAC,GAAG,KAAK,CAAC,CAAC,MAAM,IAAiB,CAAC,CAAC,KAAK;CAChF,OAAO;EAAE,WAAW,OAAO,IAAI;EAAG,eAAe,OAAO,QAAQ;CAAE;AACpE;AAEA,SAAgB,uBAAuB,OAAoD;CACzF,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,cAAc,MAAM,SAAS,KAAK,CAAC,cAAc,MAAM,aAAa,GAAG,OAAO,KAAA;CACvG,OAAO;EAAE,WAAW,MAAM;EAAW,eAAe,MAAM;CAAc;AAC1E;AAEA,SAAgB,0BAA0B,SAAiB,SAAyC;CAClG,MAAM,WAAqB,CAAC;CAC5B,IAAI,QAAQ,UAAU,SAAS,GAAG,SAAS,KAAK,iBAAiB,QAAQ,UAAU,KAAK,IAAI,EAAE,gBAAgB;CAC9G,IAAI,QAAQ,cAAc,SAAS,GACjC,SAAS,KAAK,qBAAqB,QAAQ,cAAc,KAAK,IAAI,EAAE,oBAAoB;CAE1F,MAAM,aAAa,QAAQ,QAAQ,sBAAsB,EAAE,CAAC,CAAC,KAAK;CAClE,OAAO,SAAS,SAAS,IAAI,GAAG,WAAW,MAAM,SAAS,KAAK,MAAM,MAAM;AAC7E"}
|
|
@@ -303,9 +303,10 @@ function mergeFileDetails(current, fileOps, additional) {
|
|
|
303
303
|
...fileOps ? [...fileOps.read] : []
|
|
304
304
|
]);
|
|
305
305
|
for (const path of modified) read.delete(path);
|
|
306
|
+
const recent = (paths) => [...paths].slice(-500).sort();
|
|
306
307
|
return {
|
|
307
|
-
readFiles:
|
|
308
|
-
modifiedFiles:
|
|
308
|
+
readFiles: recent(read),
|
|
309
|
+
modifiedFiles: recent(modified)
|
|
309
310
|
};
|
|
310
311
|
}
|
|
311
312
|
function fileDetailsFromUnknown(value) {
|
|
@@ -462,4 +463,4 @@ Object.defineProperty(exports, "withCanonicalFileSections", {
|
|
|
462
463
|
}
|
|
463
464
|
});
|
|
464
465
|
|
|
465
|
-
//# sourceMappingURL=compactionPolicy-
|
|
466
|
+
//# sourceMappingURL=compactionPolicy-CgYnxg8c.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compactionPolicy-_WTvdEQ2.mjs","names":[],"sources":["../src/constants/autocompact.ts","../src/services/compactionPolicy/index.ts"],"sourcesContent":["export const STATE_CUSTOM_TYPE = 'po-autocompact-state';\nexport const CHECKPOINT_MESSAGE_TYPE = 'po-autocompact-checkpoint';\nexport const CONTEXT_MESSAGE_TYPE = 'po-autocompact-context';\nexport const RESUME_MESSAGE_TYPE = 'po-autocompact-resume';\nexport const RUNTIME_STATE_MESSAGE_TYPE = 'po-autocompact-runtime-state';\nexport const STATE_VERSION = 2;\n/** Retrying a malformed checkpoint costs a full summarization call per turn, so a pass that\n * keeps failing is abandoned instead of retried for the rest of the session. */\nexport const MAX_INVALID_CHECKPOINT_ATTEMPTS = 3;\n\nexport const COMPACTION_THRESHOLDS = {\n 1: { ratio: 0.5, capTokens: 200_000 },\n 2: { ratio: 0.75, capTokens: 500_000 },\n 3: { ratio: 0.95, capTokens: 800_000 },\n} as const;\n\nexport const CHECKPOINT_HEADINGS = [\n '## Goal',\n '## Constraints & Preferences',\n '## Progress',\n '### Done',\n '### In Progress',\n '### Blocked',\n '## Key Decisions',\n '## Next Steps',\n '## Critical Context',\n] as const;\n","import {\n DEFAULT_COMPACTION_SETTINGS,\n type FileOperations,\n type SessionEntry,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\n\nimport {\n CHECKPOINT_HEADINGS,\n CHECKPOINT_MESSAGE_TYPE,\n COMPACTION_THRESHOLDS,\n CONTEXT_MESSAGE_TYPE,\n STATE_VERSION,\n} from '../../constants/autocompact';\nimport type {\n AutocompactContextDetails,\n AutocompactFileDetails,\n AutocompactRatioOverrides,\n AutocompactTokenOverrides,\n AutocompactMessage,\n AutocompactPass,\n AutocompactState,\n CheckpointDecision,\n CheckpointRequestDetails,\n ContextProjection,\n} from '../../types/autocompact';\n\n/** V4 projections have numeric timestamps and store custom messages as message entries. */\nexport type NativePolicyEntry = { id: string; timestamp: number } & (\n | { type: 'message'; message: AutocompactMessage }\n | { type: 'custom'; customType: string; data?: unknown }\n | { type: 'compaction'; summary: string; tokensBefore: number; retainedTail: AutocompactMessage[] }\n | { type: 'branch_summary'; summary: string; fromId?: string | null }\n);\nexport type CompactionPolicyEntry = SessionEntry | NativePolicyEntry;\n\nexport function customMessage(\n entry: CompactionPolicyEntry,\n): Extract<SessionEntry, { type: 'custom_message' }> | Extract<AutocompactMessage, { role: 'custom' }> | undefined {\n if (entry.type === 'custom_message') return entry;\n if (entry.type === 'message' && entry.message.role === 'custom') return entry.message;\n return undefined;\n}\n\n/** Native entries are already projected messages, not Pi journal entries. */\nexport function policyEntryMessages(entry: CompactionPolicyEntry): AutocompactMessage[] {\n if (typeof entry.timestamp === 'string') return sessionEntryToContextMessages(entry as SessionEntry);\n if (entry.type === 'message') return [entry.message];\n if (entry.type === 'compaction' && 'retainedTail' in entry) {\n return [\n {\n role: 'compactionSummary',\n summary: entry.summary,\n tokensBefore: entry.tokensBefore,\n timestamp: entry.timestamp,\n },\n ...entry.retainedTail,\n ];\n }\n if (entry.type === 'branch_summary') {\n return [{ role: 'branchSummary', summary: entry.summary, fromId: entry.fromId ?? '', timestamp: entry.timestamp }];\n }\n return [];\n}\n\nconst SHOULD_COMPACT_PATTERN = /<shouldCompact>\\s*(true|false)\\s*<\\/shouldCompact>/i;\nconst FILE_SECTION_PATTERN = /\\n*<(?:read-files|modified-files)>[\\s\\S]*?<\\/(?:read-files|modified-files)>/g;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === 'string');\n}\n\nfunction isPass(value: unknown): value is AutocompactPass {\n return value === 1 || value === 2 || value === 3;\n}\n\nfunction assistantText(entry: CompactionPolicyEntry): string | undefined {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return undefined;\n const text = entry.message.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n')\n .trim();\n return text || undefined;\n}\n\nfunction isAutocompactMessage(value: unknown): value is AutocompactMessage {\n return isRecord(value) && typeof value.role === 'string';\n}\n\nexport function contextDetailsFromUnknown(value: unknown): AutocompactContextDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (!Array.isArray(value.retainedMessages) || !value.retainedMessages.every(isAutocompactMessage)) return undefined;\n if (!isRecord(value.poAutocompact)) return undefined;\n const marker = value.poAutocompact;\n if (\n marker.version !== STATE_VERSION ||\n (marker.pass !== 2 && marker.pass !== 3) ||\n typeof marker.cycle !== 'number' ||\n typeof marker.requestId !== 'string' ||\n typeof marker.snapshotLeafId !== 'string' ||\n typeof marker.tokensBefore !== 'number'\n )\n return undefined;\n return {\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n retainedMessages: [...value.retainedMessages],\n poAutocompact: {\n version: STATE_VERSION,\n cycle: marker.cycle,\n pass: marker.pass,\n requestId: marker.requestId,\n snapshotLeafId: marker.snapshotLeafId,\n tokensBefore: marker.tokensBefore,\n },\n };\n}\n\nexport function createInitialState(): AutocompactState {\n return {\n version: STATE_VERSION,\n cycle: 1,\n pass: 1,\n phase: 'waiting',\n checkpointQueue: [],\n exhaustedPasses: [],\n invalidAttempts: 0,\n baselineTokens: 0,\n baselinePending: false,\n readFiles: [],\n modifiedFiles: [],\n };\n}\n\n/**\n * The ratios each pass fires at, with configured values folded in.\n *\n * The ladder only works if it climbs, so a configured pass never sits below the\n * one before it: a file that says pass 2 fires earlier than pass 1 gets pass 1's\n * ratio for pass 2 rather than a pass that can never contribute.\n */\nexport function compactionRatios(configured: AutocompactRatioOverrides = {}): Record<AutocompactPass, number> {\n let previous = 0;\n const ratios = {} as Record<AutocompactPass, number>;\n for (const pass of [1, 2, 3] as const) {\n const ratio = Math.max(configured[pass] ?? COMPACTION_THRESHOLDS[pass].ratio, previous);\n ratios[pass] = ratio;\n previous = ratio;\n }\n return ratios;\n}\n\nexport function thresholdTokens(\n pass: AutocompactPass,\n contextWindow: number,\n baselineTokens = 0,\n configured: AutocompactRatioOverrides = {},\n): number {\n const threshold = COMPACTION_THRESHOLDS[pass];\n const ratio = compactionRatios(configured)[pass];\n const baseline = Math.max(0, Math.min(baselineTokens, contextWindow));\n const remaining = contextWindow - baseline;\n const staged = baseline + Math.min(Math.floor(remaining * ratio), threshold.capTokens);\n // Pi compacts natively above `contextWindow - reserveTokens`. A staged threshold above that\n // point can never fire, so the ladder would silently degrade into native compaction: on a\n // 200k window the raw pass 3 ratio lands at 190_000, while Pi already compacted at 183_616.\n const nativeTrigger = contextWindow - DEFAULT_COMPACTION_SETTINGS.reserveTokens;\n return nativeTrigger > baseline ? Math.min(staged, nativeTrigger) : staged;\n}\n\n/**\n * Where every pass fires, with a matching model's absolute token checkpoints folded in.\n *\n * A configured token count replaces the ratio only when it fires earlier, so an\n * override can bring a checkpoint forward on a very large window without ever\n * pushing one past the point Pi compacts natively.\n *\n * Two rules keep the ladder usable. A token count at or below the baseline is\n * ignored, because a compaction that lands above it would otherwise satisfy that\n * pass the moment the next cycle opens and re-fire it every turn. And a pass never\n * sits below the one before it, for the same reason {@link compactionRatios}\n * climbs: `evaluateUsage` skips any pass below the one already reached, so a later\n * pass that fires first does not merely reorder the ladder, it locks the earlier\n * passes out of the cycle and forces compaction with no summary ever written.\n */\nexport function effectiveThresholds(\n contextWindow: number,\n baselineTokens = 0,\n configured: AutocompactRatioOverrides = {},\n tokenOverrides: AutocompactTokenOverrides = {},\n): Record<AutocompactPass, number> {\n let previous = 0;\n const thresholds = {} as Record<AutocompactPass, number>;\n for (const pass of [1, 2, 3] as const) {\n const ratioTokens = thresholdTokens(pass, contextWindow, baselineTokens, configured);\n const absolute = tokenOverrides[pass];\n const staged = absolute !== undefined && absolute > baselineTokens ? Math.min(ratioTokens, absolute) : ratioTokens;\n thresholds[pass] = Math.max(staged, previous);\n previous = thresholds[pass];\n }\n return thresholds;\n}\nexport function latestCheckpointArtifactEntry(\n branchEntries: readonly CompactionPolicyEntry[],\n): CompactionPolicyEntry | undefined {\n return branchEntries.findLast(\n (entry) =>\n entry.type === 'compaction' ||\n // Staged checkpoints are plain entries so they stay out of the agent's LLM context.\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n // Legacy sessions staged checkpoints as custom messages; committed markers still are.\n customMessage(entry)?.customType === CHECKPOINT_MESSAGE_TYPE ||\n customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE,\n );\n}\n\nexport function baselineUsageIsSettled(branchEntries: readonly CompactionPolicyEntry[]): boolean {\n const boundaryIndex = branchEntries.findLastIndex(\n (entry) => entry.type === 'compaction' || customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE,\n );\n return branchEntries.slice(boundaryIndex + 1).some((entry) => {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return false;\n const { stopReason, usage } = entry.message;\n if (stopReason === 'aborted' || stopReason === 'error' || !usage) return false;\n return (usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;\n });\n}\n\nexport function retainedMessagesAfterSnapshot(\n branchEntries: readonly CompactionPolicyEntry[],\n snapshotLeafId: string,\n): AutocompactMessage[] {\n const snapshotIndex = branchEntries.findIndex((entry) => entry.id === snapshotLeafId);\n if (snapshotIndex === -1) return [];\n return branchEntries\n .slice(snapshotIndex + 1)\n .filter((entry) => customMessage(entry)?.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap(policyEntryMessages);\n}\n\nexport function projectContextMessages(\n messages: AutocompactMessage[],\n branchEntries: readonly CompactionPolicyEntry[],\n): ContextProjection {\n const nativeCompactionIndex = branchEntries.findLastIndex((entry) => entry.type === 'compaction');\n const markerEntry = branchEntries\n .slice(nativeCompactionIndex + 1)\n .findLast((entry) => customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE);\n const markerMessage = markerEntry && customMessage(markerEntry);\n if (!markerEntry || !markerMessage) {\n return { messages, retainedMessageCount: 0 };\n }\n\n const details = contextDetailsFromUnknown(markerMessage.details);\n const summary = checkpointSummaryFromEntry(markerEntry);\n if (!details || !summary) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const markerMessageIndex = messages.findLastIndex(\n (message) =>\n message.role === 'custom' &&\n message.customType === CONTEXT_MESSAGE_TYPE &&\n contextDetailsFromUnknown(message.details)?.poAutocompact.requestId === details.poAutocompact.requestId,\n );\n if (markerMessageIndex === -1) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const summaryMessage: AutocompactMessage = {\n role: 'compactionSummary',\n summary,\n tokensBefore: details.poAutocompact.tokensBefore,\n timestamp: messages[markerMessageIndex]?.timestamp ?? Date.now(),\n };\n return {\n messages: [summaryMessage, ...details.retainedMessages, ...messages.slice(markerMessageIndex + 1)],\n marker: details.poAutocompact,\n retainedMessageCount: details.retainedMessages.length,\n };\n}\n\nexport function fileOperationsFromMessages(messages: AutocompactMessage[]): FileOperations {\n const fileOps: FileOperations = { read: new Set(), written: new Set(), edited: new Set() };\n for (const message of messages) {\n if (message.role !== 'assistant') continue;\n for (const block of message.content) {\n if (block.type !== 'toolCall') continue;\n const path = typeof block.arguments.path === 'string' ? block.arguments.path : undefined;\n if (!path) continue;\n if (block.name === 'read') fileOps.read.add(path);\n else if (block.name === 'write') fileOps.written.add(path);\n else if (block.name === 'edit') fileOps.edited.add(path);\n }\n }\n return fileOps;\n}\n\nexport function parseState(value: unknown): AutocompactState | undefined {\n if (!isRecord(value)) return undefined;\n if (value.version !== STATE_VERSION || typeof value.cycle !== 'number' || !isPass(value.pass)) return undefined;\n if (\n value.phase !== 'waiting' &&\n value.phase !== 'checkpoint_pending' &&\n value.phase !== 'checkpoint_ready' &&\n value.phase !== 'compacting'\n )\n return undefined;\n const baselineTokens = value.baselineTokens ?? 0;\n if (typeof baselineTokens !== 'number' || baselineTokens < 0) return undefined;\n const baselinePending = value.baselinePending ?? false;\n if (typeof baselinePending !== 'boolean') return undefined;\n const checkpointQueue = value.checkpointQueue ?? [];\n if (\n !Array.isArray(checkpointQueue) ||\n !checkpointQueue.every(isPass) ||\n checkpointQueue.some((pass, index) => index > 0 && pass <= checkpointQueue[index - 1]!)\n )\n return undefined;\n // Sessions persisted before bounded retry landed simply have no attempt history to restore.\n const exhaustedPasses = value.exhaustedPasses ?? [];\n if (!Array.isArray(exhaustedPasses) || !exhaustedPasses.every(isPass)) return undefined;\n const invalidAttempts = value.invalidAttempts ?? 0;\n if (typeof invalidAttempts !== 'number' || invalidAttempts < 0) return undefined;\n if (!isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (value.requestId !== undefined && typeof value.requestId !== 'string') return undefined;\n if (value.compactionPass !== undefined && value.compactionPass !== 2 && value.compactionPass !== 3) return undefined;\n if ('latestCheckpointEntryId' in value) return undefined;\n if (value.latestCheckpointSnapshotLeafId !== undefined && typeof value.latestCheckpointSnapshotLeafId !== 'string')\n return undefined;\n if (value.lastAttemptLeafId !== undefined && typeof value.lastAttemptLeafId !== 'string') return undefined;\n if (value.snapshotLeafId !== undefined && typeof value.snapshotLeafId !== 'string') return undefined;\n if (value.snapshotTokens !== undefined && (typeof value.snapshotTokens !== 'number' || value.snapshotTokens < 0))\n return undefined;\n if (value.pendingCheckpoint !== undefined && typeof value.pendingCheckpoint !== 'string') return undefined;\n\n return {\n version: STATE_VERSION,\n cycle: value.cycle,\n pass: value.pass,\n phase: value.phase,\n checkpointQueue: [...checkpointQueue],\n exhaustedPasses: [...exhaustedPasses],\n invalidAttempts,\n baselineTokens,\n baselinePending,\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n ...(value.requestId ? { requestId: value.requestId } : {}),\n ...(value.compactionPass ? { compactionPass: value.compactionPass } : {}),\n ...(value.latestCheckpointSnapshotLeafId\n ? { latestCheckpointSnapshotLeafId: value.latestCheckpointSnapshotLeafId }\n : {}),\n ...(value.lastAttemptLeafId ? { lastAttemptLeafId: value.lastAttemptLeafId } : {}),\n ...(value.snapshotLeafId ? { snapshotLeafId: value.snapshotLeafId } : {}),\n ...(value.snapshotTokens !== undefined ? { snapshotTokens: value.snapshotTokens } : {}),\n ...(value.pendingCheckpoint ? { pendingCheckpoint: value.pendingCheckpoint } : {}),\n };\n}\n\nexport function checkpointSummaryFromEntry(entry: CompactionPolicyEntry | undefined): string | undefined {\n if (!entry) return undefined;\n if (entry.type === 'compaction') return entry.summary.trim() || undefined;\n if (entry.type === 'custom') {\n return isRecord(entry.data) && typeof entry.data.summary === 'string'\n ? entry.data.summary.trim() || undefined\n : undefined;\n }\n const marker = customMessage(entry);\n if (marker) {\n const content =\n typeof marker.content === 'string'\n ? marker.content\n : marker.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n return content.trim() || undefined;\n }\n return assistantText(entry);\n}\n\nexport function parseCheckpointDecision(response: string): CheckpointDecision {\n const match = response.match(SHOULD_COMPACT_PATTERN);\n const summary = response.replace(SHOULD_COMPACT_PATTERN, '').trim();\n if (!match) return { summary };\n return { summary, shouldCompact: match[1]?.toLowerCase() === 'true' };\n}\n\nexport function isStructuredCheckpoint(summary: string): boolean {\n return CHECKPOINT_HEADINGS.every((heading) => summary.includes(heading));\n}\n\nexport function createRequestId(\n sessionId: string,\n cycle: number,\n pass: AutocompactPass,\n leafId: string | null,\n): string {\n return `${sessionId}:${cycle}:${pass}:${leafId ?? 'root'}`;\n}\n\nexport function checkpointRequestDetails(\n cycle: number,\n pass: AutocompactPass,\n requestId: string,\n): CheckpointRequestDetails {\n return { version: STATE_VERSION, cycle, pass, requestId };\n}\n\nexport function mergeFileDetails(\n current: AutocompactFileDetails,\n fileOps?: FileOperations,\n additional?: AutocompactFileDetails,\n): AutocompactFileDetails {\n const modified = new Set([\n ...current.modifiedFiles,\n ...(additional?.modifiedFiles ?? []),\n ...(fileOps ? [...fileOps.edited, ...fileOps.written] : []),\n ]);\n const read = new Set([...current.readFiles, ...(additional?.readFiles ?? []), ...(fileOps ? [...fileOps.read] : [])]);\n for (const path of modified) read.delete(path);\n return { readFiles: [...read].sort(), modifiedFiles: [...modified].sort() };\n}\n\nexport function fileDetailsFromUnknown(value: unknown): AutocompactFileDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n return { readFiles: value.readFiles, modifiedFiles: value.modifiedFiles };\n}\n\nexport function withCanonicalFileSections(summary: string, details: AutocompactFileDetails): string {\n const sections: string[] = [];\n if (details.readFiles.length > 0) sections.push(`<read-files>\\n${details.readFiles.join('\\n')}\\n</read-files>`);\n if (details.modifiedFiles.length > 0) {\n sections.push(`<modified-files>\\n${details.modifiedFiles.join('\\n')}\\n</modified-files>`);\n }\n const normalized = summary.replace(FILE_SECTION_PATTERN, '').trim();\n return sections.length > 0 ? `${normalized}\\n\\n${sections.join('\\n\\n')}` : normalized;\n}\n"],"mappings":";;AAAA,MAAa,oBAAoB;AACjC,MAAa,0BAA0B;AACvC,MAAa,uBAAuB;AACpC,MAAa,sBAAsB;AACnC,MAAa,6BAA6B;AAM1C,MAAa,wBAAwB;CACnC,GAAG;EAAE,OAAO;EAAK,WAAW;CAAQ;CACpC,GAAG;EAAE,OAAO;EAAM,WAAW;CAAQ;CACrC,GAAG;EAAE,OAAO;EAAM,WAAW;CAAQ;AACvC;AAEA,MAAa,sBAAsB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;ACUA,SAAgB,cACd,OACiH;CACjH,IAAI,MAAM,SAAS,kBAAk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7C,OAAO;EAAE,WAAW,CAAC,GAAG,IAAI,CAAC,CAAC,KAAK;EAAG,eAAe,CAAC,GAAG,QAAQ,CAAC,CAAC,KAAK;CAAE;AAC5E;AAEA,SAAgB,uBAAuB,OAAoD;CACzF,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,cAAc,MAAM,SAAS,KAAK,CAAC,cAAc,MAAM,aAAa,GAAG,OAAO,KAAA;CACvG,OAAO;EAAE,WAAW,MAAM;EAAW,eAAe,MAAM;CAAc;AAC1E;AAEA,SAAgB,0BAA0B,SAAiB,SAAyC;CAClG,MAAM,WAAqB,CAAC;CAC5B,IAAI,QAAQ,UAAU,SAAS,GAAG,SAAS,KAAK,iBAAiB,QAAQ,UAAU,KAAK,IAAI,EAAE,gBAAgB;CAC9G,IAAI,QAAQ,cAAc,SAAS,GACjC,SAAS,KAAK,qBAAqB,QAAQ,cAAc,KAAK,IAAI,EAAE,oBAAoB;CAE1F,MAAM,aAAa,QAAQ,QAAQ,sBAAsB,EAAE,CAAC,CAAC,KAAK;CAClE,OAAO,SAAS,SAAS,IAAI,GAAG,WAAW,MAAM,SAAS,KAAK,MAAM,MAAM;AAC7E"}
|
|
1
|
+
{"version":3,"file":"compactionPolicy-CgYnxg8c.cjs","names":["DEFAULT_COMPACTION_SETTINGS"],"sources":["../src/constants/autocompact.ts","../src/services/compactionPolicy/index.ts"],"sourcesContent":["export const STATE_CUSTOM_TYPE = 'po-autocompact-state';\nexport const CHECKPOINT_MESSAGE_TYPE = 'po-autocompact-checkpoint';\nexport const CONTEXT_MESSAGE_TYPE = 'po-autocompact-context';\nexport const RESUME_MESSAGE_TYPE = 'po-autocompact-resume';\nexport const RUNTIME_STATE_MESSAGE_TYPE = 'po-autocompact-runtime-state';\nexport const STATE_VERSION = 2;\n/** Retrying a malformed checkpoint costs a full summarization call per turn, so a pass that\n * keeps failing is abandoned instead of retried for the rest of the session. */\nexport const MAX_INVALID_CHECKPOINT_ATTEMPTS = 3;\n\nexport const COMPACTION_THRESHOLDS = {\n 1: { ratio: 0.5, capTokens: 200_000 },\n 2: { ratio: 0.75, capTokens: 500_000 },\n 3: { ratio: 0.95, capTokens: 800_000 },\n} as const;\n\nexport const CHECKPOINT_HEADINGS = [\n '## Goal',\n '## Constraints & Preferences',\n '## Progress',\n '### Done',\n '### In Progress',\n '### Blocked',\n '## Key Decisions',\n '## Next Steps',\n '## Critical Context',\n] as const;\n","import {\n DEFAULT_COMPACTION_SETTINGS,\n type FileOperations,\n type SessionEntry,\n sessionEntryToContextMessages,\n} from '@earendil-works/pi-coding-agent';\n\nimport {\n CHECKPOINT_HEADINGS,\n CHECKPOINT_MESSAGE_TYPE,\n COMPACTION_THRESHOLDS,\n CONTEXT_MESSAGE_TYPE,\n STATE_VERSION,\n} from '../../constants/autocompact';\nimport type {\n AutocompactContextDetails,\n AutocompactFileDetails,\n AutocompactRatioOverrides,\n AutocompactTokenOverrides,\n AutocompactMessage,\n AutocompactPass,\n AutocompactState,\n CheckpointDecision,\n CheckpointRequestDetails,\n ContextProjection,\n} from '../../types/autocompact';\n\n/** V4 projections have numeric timestamps and store custom messages as message entries. */\nexport type NativePolicyEntry = { id: string; timestamp: number } & (\n | { type: 'message'; message: AutocompactMessage }\n | { type: 'custom'; customType: string; data?: unknown }\n | { type: 'compaction'; summary: string; tokensBefore: number; retainedTail: AutocompactMessage[] }\n | { type: 'branch_summary'; summary: string; fromId?: string | null }\n);\nexport type CompactionPolicyEntry = SessionEntry | NativePolicyEntry;\n\nexport function customMessage(\n entry: CompactionPolicyEntry,\n): Extract<SessionEntry, { type: 'custom_message' }> | Extract<AutocompactMessage, { role: 'custom' }> | undefined {\n if (entry.type === 'custom_message') return entry;\n if (entry.type === 'message' && entry.message.role === 'custom') return entry.message;\n return undefined;\n}\n\n/** Native entries are already projected messages, not Pi journal entries. */\nexport function policyEntryMessages(entry: CompactionPolicyEntry): AutocompactMessage[] {\n if (typeof entry.timestamp === 'string') return sessionEntryToContextMessages(entry as SessionEntry);\n if (entry.type === 'message') return [entry.message];\n if (entry.type === 'compaction' && 'retainedTail' in entry) {\n return [\n {\n role: 'compactionSummary',\n summary: entry.summary,\n tokensBefore: entry.tokensBefore,\n timestamp: entry.timestamp,\n },\n ...entry.retainedTail,\n ];\n }\n if (entry.type === 'branch_summary') {\n return [{ role: 'branchSummary', summary: entry.summary, fromId: entry.fromId ?? '', timestamp: entry.timestamp }];\n }\n return [];\n}\n\nconst SHOULD_COMPACT_PATTERN = /<shouldCompact>\\s*(true|false)\\s*<\\/shouldCompact>/i;\nconst FILE_SECTION_PATTERN = /\\n*<(?:read-files|modified-files)>[\\s\\S]*?<\\/(?:read-files|modified-files)>/g;\n// ponytail: the most recently touched paths per list; older ones fall out of state and summaries.\n// Raise it, or move file history to the artifact mirror, if long sessions need the full list.\nconst MAX_FILE_DETAILS = 500;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === 'string');\n}\n\nfunction isPass(value: unknown): value is AutocompactPass {\n return value === 1 || value === 2 || value === 3;\n}\n\nfunction assistantText(entry: CompactionPolicyEntry): string | undefined {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return undefined;\n const text = entry.message.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n')\n .trim();\n return text || undefined;\n}\n\nfunction isAutocompactMessage(value: unknown): value is AutocompactMessage {\n return isRecord(value) && typeof value.role === 'string';\n}\n\nexport function contextDetailsFromUnknown(value: unknown): AutocompactContextDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (!Array.isArray(value.retainedMessages) || !value.retainedMessages.every(isAutocompactMessage)) return undefined;\n if (!isRecord(value.poAutocompact)) return undefined;\n const marker = value.poAutocompact;\n if (\n marker.version !== STATE_VERSION ||\n (marker.pass !== 2 && marker.pass !== 3) ||\n typeof marker.cycle !== 'number' ||\n typeof marker.requestId !== 'string' ||\n typeof marker.snapshotLeafId !== 'string' ||\n typeof marker.tokensBefore !== 'number'\n )\n return undefined;\n return {\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n retainedMessages: [...value.retainedMessages],\n poAutocompact: {\n version: STATE_VERSION,\n cycle: marker.cycle,\n pass: marker.pass,\n requestId: marker.requestId,\n snapshotLeafId: marker.snapshotLeafId,\n tokensBefore: marker.tokensBefore,\n },\n };\n}\n\nexport function createInitialState(): AutocompactState {\n return {\n version: STATE_VERSION,\n cycle: 1,\n pass: 1,\n phase: 'waiting',\n checkpointQueue: [],\n exhaustedPasses: [],\n invalidAttempts: 0,\n baselineTokens: 0,\n baselinePending: false,\n readFiles: [],\n modifiedFiles: [],\n };\n}\n\n/**\n * The ratios each pass fires at, with configured values folded in.\n *\n * The ladder only works if it climbs, so a configured pass never sits below the\n * one before it: a file that says pass 2 fires earlier than pass 1 gets pass 1's\n * ratio for pass 2 rather than a pass that can never contribute.\n */\nexport function compactionRatios(configured: AutocompactRatioOverrides = {}): Record<AutocompactPass, number> {\n let previous = 0;\n const ratios = {} as Record<AutocompactPass, number>;\n for (const pass of [1, 2, 3] as const) {\n const ratio = Math.max(configured[pass] ?? COMPACTION_THRESHOLDS[pass].ratio, previous);\n ratios[pass] = ratio;\n previous = ratio;\n }\n return ratios;\n}\n\nexport function thresholdTokens(\n pass: AutocompactPass,\n contextWindow: number,\n baselineTokens = 0,\n configured: AutocompactRatioOverrides = {},\n): number {\n const threshold = COMPACTION_THRESHOLDS[pass];\n const ratio = compactionRatios(configured)[pass];\n const baseline = Math.max(0, Math.min(baselineTokens, contextWindow));\n const remaining = contextWindow - baseline;\n const staged = baseline + Math.min(Math.floor(remaining * ratio), threshold.capTokens);\n // Pi compacts natively above `contextWindow - reserveTokens`. A staged threshold above that\n // point can never fire, so the ladder would silently degrade into native compaction: on a\n // 200k window the raw pass 3 ratio lands at 190_000, while Pi already compacted at 183_616.\n const nativeTrigger = contextWindow - DEFAULT_COMPACTION_SETTINGS.reserveTokens;\n return nativeTrigger > baseline ? Math.min(staged, nativeTrigger) : staged;\n}\n\n/**\n * Where every pass fires, with a matching model's absolute token checkpoints folded in.\n *\n * A configured token count replaces the ratio only when it fires earlier, so an\n * override can bring a checkpoint forward on a very large window without ever\n * pushing one past the point Pi compacts natively.\n *\n * Two rules keep the ladder usable. A token count at or below the baseline is\n * ignored, because a compaction that lands above it would otherwise satisfy that\n * pass the moment the next cycle opens and re-fire it every turn. And a pass never\n * sits below the one before it, for the same reason {@link compactionRatios}\n * climbs: `evaluateUsage` skips any pass below the one already reached, so a later\n * pass that fires first does not merely reorder the ladder, it locks the earlier\n * passes out of the cycle and forces compaction with no summary ever written.\n */\nexport function effectiveThresholds(\n contextWindow: number,\n baselineTokens = 0,\n configured: AutocompactRatioOverrides = {},\n tokenOverrides: AutocompactTokenOverrides = {},\n): Record<AutocompactPass, number> {\n let previous = 0;\n const thresholds = {} as Record<AutocompactPass, number>;\n for (const pass of [1, 2, 3] as const) {\n const ratioTokens = thresholdTokens(pass, contextWindow, baselineTokens, configured);\n const absolute = tokenOverrides[pass];\n const staged = absolute !== undefined && absolute > baselineTokens ? Math.min(ratioTokens, absolute) : ratioTokens;\n thresholds[pass] = Math.max(staged, previous);\n previous = thresholds[pass];\n }\n return thresholds;\n}\nexport function latestCheckpointArtifactEntry(\n branchEntries: readonly CompactionPolicyEntry[],\n): CompactionPolicyEntry | undefined {\n return branchEntries.findLast(\n (entry) =>\n entry.type === 'compaction' ||\n // Staged checkpoints are plain entries so they stay out of the agent's LLM context.\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n // Legacy sessions staged checkpoints as custom messages; committed markers still are.\n customMessage(entry)?.customType === CHECKPOINT_MESSAGE_TYPE ||\n customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE,\n );\n}\n\nexport function baselineUsageIsSettled(branchEntries: readonly CompactionPolicyEntry[]): boolean {\n const boundaryIndex = branchEntries.findLastIndex(\n (entry) => entry.type === 'compaction' || customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE,\n );\n return branchEntries.slice(boundaryIndex + 1).some((entry) => {\n if (entry.type !== 'message' || entry.message.role !== 'assistant') return false;\n const { stopReason, usage } = entry.message;\n if (stopReason === 'aborted' || stopReason === 'error' || !usage) return false;\n return (usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;\n });\n}\n\nexport function retainedMessagesAfterSnapshot(\n branchEntries: readonly CompactionPolicyEntry[],\n snapshotLeafId: string,\n): AutocompactMessage[] {\n const snapshotIndex = branchEntries.findIndex((entry) => entry.id === snapshotLeafId);\n if (snapshotIndex === -1) return [];\n return branchEntries\n .slice(snapshotIndex + 1)\n .filter((entry) => customMessage(entry)?.customType !== CHECKPOINT_MESSAGE_TYPE)\n .flatMap(policyEntryMessages);\n}\n\nexport function projectContextMessages(\n messages: AutocompactMessage[],\n branchEntries: readonly CompactionPolicyEntry[],\n): ContextProjection {\n const nativeCompactionIndex = branchEntries.findLastIndex((entry) => entry.type === 'compaction');\n const markerEntry = branchEntries\n .slice(nativeCompactionIndex + 1)\n .findLast((entry) => customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE);\n const markerMessage = markerEntry && customMessage(markerEntry);\n if (!markerEntry || !markerMessage) {\n return { messages, retainedMessageCount: 0 };\n }\n\n const details = contextDetailsFromUnknown(markerMessage.details);\n const summary = checkpointSummaryFromEntry(markerEntry);\n if (!details || !summary) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const markerMessageIndex = messages.findLastIndex(\n (message) =>\n message.role === 'custom' &&\n message.customType === CONTEXT_MESSAGE_TYPE &&\n contextDetailsFromUnknown(message.details)?.poAutocompact.requestId === details.poAutocompact.requestId,\n );\n if (markerMessageIndex === -1) return { messages, invalidMarker: true, retainedMessageCount: 0 };\n\n const summaryMessage: AutocompactMessage = {\n role: 'compactionSummary',\n summary,\n tokensBefore: details.poAutocompact.tokensBefore,\n timestamp: messages[markerMessageIndex]?.timestamp ?? Date.now(),\n };\n return {\n messages: [summaryMessage, ...details.retainedMessages, ...messages.slice(markerMessageIndex + 1)],\n marker: details.poAutocompact,\n retainedMessageCount: details.retainedMessages.length,\n };\n}\n\nexport function fileOperationsFromMessages(messages: AutocompactMessage[]): FileOperations {\n const fileOps: FileOperations = { read: new Set(), written: new Set(), edited: new Set() };\n for (const message of messages) {\n if (message.role !== 'assistant') continue;\n for (const block of message.content) {\n if (block.type !== 'toolCall') continue;\n const path = typeof block.arguments.path === 'string' ? block.arguments.path : undefined;\n if (!path) continue;\n if (block.name === 'read') fileOps.read.add(path);\n else if (block.name === 'write') fileOps.written.add(path);\n else if (block.name === 'edit') fileOps.edited.add(path);\n }\n }\n return fileOps;\n}\n\nexport function parseState(value: unknown): AutocompactState | undefined {\n if (!isRecord(value)) return undefined;\n if (value.version !== STATE_VERSION || typeof value.cycle !== 'number' || !isPass(value.pass)) return undefined;\n if (\n value.phase !== 'waiting' &&\n value.phase !== 'checkpoint_pending' &&\n value.phase !== 'checkpoint_ready' &&\n value.phase !== 'compacting'\n )\n return undefined;\n const baselineTokens = value.baselineTokens ?? 0;\n if (typeof baselineTokens !== 'number' || baselineTokens < 0) return undefined;\n const baselinePending = value.baselinePending ?? false;\n if (typeof baselinePending !== 'boolean') return undefined;\n const checkpointQueue = value.checkpointQueue ?? [];\n if (\n !Array.isArray(checkpointQueue) ||\n !checkpointQueue.every(isPass) ||\n checkpointQueue.some((pass, index) => index > 0 && pass <= checkpointQueue[index - 1]!)\n )\n return undefined;\n // Sessions persisted before bounded retry landed simply have no attempt history to restore.\n const exhaustedPasses = value.exhaustedPasses ?? [];\n if (!Array.isArray(exhaustedPasses) || !exhaustedPasses.every(isPass)) return undefined;\n const invalidAttempts = value.invalidAttempts ?? 0;\n if (typeof invalidAttempts !== 'number' || invalidAttempts < 0) return undefined;\n if (!isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n if (value.requestId !== undefined && typeof value.requestId !== 'string') return undefined;\n if (value.compactionPass !== undefined && value.compactionPass !== 2 && value.compactionPass !== 3) return undefined;\n if ('latestCheckpointEntryId' in value) return undefined;\n if (value.latestCheckpointSnapshotLeafId !== undefined && typeof value.latestCheckpointSnapshotLeafId !== 'string')\n return undefined;\n if (value.lastAttemptLeafId !== undefined && typeof value.lastAttemptLeafId !== 'string') return undefined;\n if (value.snapshotLeafId !== undefined && typeof value.snapshotLeafId !== 'string') return undefined;\n if (value.snapshotTokens !== undefined && (typeof value.snapshotTokens !== 'number' || value.snapshotTokens < 0))\n return undefined;\n if (value.pendingCheckpoint !== undefined && typeof value.pendingCheckpoint !== 'string') return undefined;\n\n return {\n version: STATE_VERSION,\n cycle: value.cycle,\n pass: value.pass,\n phase: value.phase,\n checkpointQueue: [...checkpointQueue],\n exhaustedPasses: [...exhaustedPasses],\n invalidAttempts,\n baselineTokens,\n baselinePending,\n readFiles: [...value.readFiles],\n modifiedFiles: [...value.modifiedFiles],\n ...(value.requestId ? { requestId: value.requestId } : {}),\n ...(value.compactionPass ? { compactionPass: value.compactionPass } : {}),\n ...(value.latestCheckpointSnapshotLeafId\n ? { latestCheckpointSnapshotLeafId: value.latestCheckpointSnapshotLeafId }\n : {}),\n ...(value.lastAttemptLeafId ? { lastAttemptLeafId: value.lastAttemptLeafId } : {}),\n ...(value.snapshotLeafId ? { snapshotLeafId: value.snapshotLeafId } : {}),\n ...(value.snapshotTokens !== undefined ? { snapshotTokens: value.snapshotTokens } : {}),\n ...(value.pendingCheckpoint ? { pendingCheckpoint: value.pendingCheckpoint } : {}),\n };\n}\n\nexport function checkpointSummaryFromEntry(entry: CompactionPolicyEntry | undefined): string | undefined {\n if (!entry) return undefined;\n if (entry.type === 'compaction') return entry.summary.trim() || undefined;\n if (entry.type === 'custom') {\n return isRecord(entry.data) && typeof entry.data.summary === 'string'\n ? entry.data.summary.trim() || undefined\n : undefined;\n }\n const marker = customMessage(entry);\n if (marker) {\n const content =\n typeof marker.content === 'string'\n ? marker.content\n : marker.content\n .filter((block) => block.type === 'text')\n .map((block) => block.text)\n .join('\\n');\n return content.trim() || undefined;\n }\n return assistantText(entry);\n}\n\nexport function parseCheckpointDecision(response: string): CheckpointDecision {\n const match = response.match(SHOULD_COMPACT_PATTERN);\n const summary = response.replace(SHOULD_COMPACT_PATTERN, '').trim();\n if (!match) return { summary };\n return { summary, shouldCompact: match[1]?.toLowerCase() === 'true' };\n}\n\nexport function isStructuredCheckpoint(summary: string): boolean {\n return CHECKPOINT_HEADINGS.every((heading) => summary.includes(heading));\n}\n\nexport function createRequestId(\n sessionId: string,\n cycle: number,\n pass: AutocompactPass,\n leafId: string | null,\n): string {\n return `${sessionId}:${cycle}:${pass}:${leafId ?? 'root'}`;\n}\n\nexport function checkpointRequestDetails(\n cycle: number,\n pass: AutocompactPass,\n requestId: string,\n): CheckpointRequestDetails {\n return { version: STATE_VERSION, cycle, pass, requestId };\n}\n\nexport function mergeFileDetails(\n current: AutocompactFileDetails,\n fileOps?: FileOperations,\n additional?: AutocompactFileDetails,\n): AutocompactFileDetails {\n const modified = new Set([\n ...current.modifiedFiles,\n ...(additional?.modifiedFiles ?? []),\n ...(fileOps ? [...fileOps.edited, ...fileOps.written] : []),\n ]);\n const read = new Set([...current.readFiles, ...(additional?.readFiles ?? []), ...(fileOps ? [...fileOps.read] : [])]);\n for (const path of modified) read.delete(path);\n // Sets keep insertion order, so the tail holds the newest paths.\n const recent = (paths: Set<string>) => [...paths].slice(-MAX_FILE_DETAILS).sort();\n return { readFiles: recent(read), modifiedFiles: recent(modified) };\n}\n\nexport function fileDetailsFromUnknown(value: unknown): AutocompactFileDetails | undefined {\n if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return undefined;\n return { readFiles: value.readFiles, modifiedFiles: value.modifiedFiles };\n}\n\nexport function withCanonicalFileSections(summary: string, details: AutocompactFileDetails): string {\n const sections: string[] = [];\n if (details.readFiles.length > 0) sections.push(`<read-files>\\n${details.readFiles.join('\\n')}\\n</read-files>`);\n if (details.modifiedFiles.length > 0) {\n sections.push(`<modified-files>\\n${details.modifiedFiles.join('\\n')}\\n</modified-files>`);\n }\n const normalized = summary.replace(FILE_SECTION_PATTERN, '').trim();\n return sections.length > 0 ? `${normalized}\\n\\n${sections.join('\\n\\n')}` : normalized;\n}\n"],"mappings":";;AAAA,MAAa,oBAAoB;AACjC,MAAa,0BAA0B;AACvC,MAAa,uBAAuB;AACpC,MAAa,sBAAsB;AACnC,MAAa,6BAA6B;AAM1C,MAAa,wBAAwB;CACnC,GAAG;EAAE,OAAO;EAAK,WAAW;CAAQ;CACpC,GAAG;EAAE,OAAO;EAAM,WAAW;CAAQ;CACrC,GAAG;EAAE,OAAO;EAAM,WAAW;CAAQ;AACvC;AAEA,MAAa,sBAAsB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;ACUA,SAAgB,cACd,OACiH;CACjH,IAAI,MAAM,SAAS,kBAAkB,OAAO;CAC5C,IAAI,MAAM,SAAS,aAAa,MAAM,QAAQ,SAAS,UAAU,OAAO,MAAM;AAEhF;AAuBA,MAAM,yBAAyB;AAC/B,MAAM,uBAAuB;AAK7B,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAEA,SAAS,cAAc,OAAmC;CACxD,OAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,SAAS,OAAO,SAAS,QAAQ;AAC/E;AAEA,SAAS,OAAO,OAA0C;CACxD,OAAO,UAAU,KAAK,UAAU,KAAK,UAAU;AACjD;AAEA,SAAS,cAAc,OAAkD;CACvE,IAAI,MAAM,SAAS,aAAa,MAAM,QAAQ,SAAS,aAAa,OAAO,KAAA;CAM3E,OALa,MAAM,QAAQ,QACxB,QAAQ,UAAU,MAAM,SAAS,MAAM,CAAC,CACxC,KAAK,UAAU,MAAM,IAAI,CAAC,CAC1B,KAAK,IAAI,CAAC,CACV,KACO,KAAK,KAAA;A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B;CAE1F,MAAM,aAAa,QAAQ,QAAQ,sBAAsB,EAAE,CAAC,CAAC,KAAK;CAClE,OAAO,SAAS,SAAS,IAAI,GAAG,WAAW,MAAM,SAAS,KAAK,MAAM,MAAM;AAC7E"}
|
|
@@ -2,7 +2,7 @@ Object.defineProperties(exports, {
|
|
|
2
2
|
__esModule: { value: true },
|
|
3
3
|
[Symbol.toStringTag]: { value: "Module" }
|
|
4
4
|
});
|
|
5
|
-
const require_compactionPolicy = require("../compactionPolicy-
|
|
5
|
+
const require_compactionPolicy = require("../compactionPolicy-CgYnxg8c.cjs");
|
|
6
6
|
let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
|
|
7
7
|
let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
|
|
8
8
|
let _agimon_ai_po_core_telemetry = require("@agimon-ai/po-core/telemetry");
|
|
@@ -243,6 +243,11 @@ function committedFields(entry) {
|
|
|
243
243
|
}
|
|
244
244
|
};
|
|
245
245
|
}
|
|
246
|
+
/** The only entries `wantedHistory` reads, so mirrors can scan history without keeping the rest. */
|
|
247
|
+
function isHistoryEntry(entry) {
|
|
248
|
+
const type = require_compactionPolicy.customMessage(entry)?.customType;
|
|
249
|
+
return entry.type === "compaction" || entry.type === "custom" && entry.customType === "po-autocompact-checkpoint" || type === "po-autocompact-checkpoint" || type === "po-autocompact-context";
|
|
250
|
+
}
|
|
246
251
|
/** Number commits along the active branch so a rewind rewrites the same epoch folders. */
|
|
247
252
|
function wantedHistory(entries) {
|
|
248
253
|
const files = [];
|
|
@@ -457,7 +462,29 @@ function createNativeAutocompact(dependencies = {}) {
|
|
|
457
462
|
"autocompact.checkpoint.exhausted": attempts >= 3
|
|
458
463
|
})))]);
|
|
459
464
|
};
|
|
460
|
-
const
|
|
465
|
+
const matching = async (execution, keep, stopAt) => {
|
|
466
|
+
const entries = [];
|
|
467
|
+
for await (const record of execution.session.entriesNewestFirst()) {
|
|
468
|
+
const entry = record;
|
|
469
|
+
if (entry.id === stopAt) break;
|
|
470
|
+
if (keep(entry)) entries.push(entry);
|
|
471
|
+
}
|
|
472
|
+
return entries.reverse();
|
|
473
|
+
};
|
|
474
|
+
const policyEntries = async (execution, withCheckpoint) => {
|
|
475
|
+
const entries = [...await execution.session.entries({
|
|
476
|
+
type: "custom",
|
|
477
|
+
customType: PLAN_DOCUMENT_ENTRY,
|
|
478
|
+
limit: 1
|
|
479
|
+
})];
|
|
480
|
+
if (withCheckpoint) for await (const record of execution.session.entriesNewestFirst()) {
|
|
481
|
+
const entry = record;
|
|
482
|
+
if (!require_compactionPolicy.latestCheckpointArtifactEntry([entry])) continue;
|
|
483
|
+
entries.push(entry);
|
|
484
|
+
break;
|
|
485
|
+
}
|
|
486
|
+
return entries;
|
|
487
|
+
};
|
|
461
488
|
const contextBranch = async (execution) => {
|
|
462
489
|
const entries = [];
|
|
463
490
|
let foundLeaf = false;
|
|
@@ -480,7 +507,7 @@ function createNativeAutocompact(dependencies = {}) {
|
|
|
480
507
|
enqueue(async () => {
|
|
481
508
|
mirrorQueued = false;
|
|
482
509
|
try {
|
|
483
|
-
await mirrorCompactionHistory((0, _agimon_ai_po_artifact_artifactFiles.artifactRoot)(execution.sessionId, execution.environment), await
|
|
510
|
+
await mirrorCompactionHistory((0, _agimon_ai_po_artifact_artifactFiles.artifactRoot)(execution.sessionId, execution.environment), await matching(execution, isHistoryEntry));
|
|
484
511
|
} catch (error) {
|
|
485
512
|
const warn = historyWarnedSession !== execution.sessionId;
|
|
486
513
|
historyWarnedSession = execution.sessionId;
|
|
@@ -540,13 +567,14 @@ function createNativeAutocompact(dependencies = {}) {
|
|
|
540
567
|
const configuration = configured(execution);
|
|
541
568
|
if (!configuration.enabled || !execution.textCompletion?.summarize) return;
|
|
542
569
|
try {
|
|
543
|
-
const entries = await
|
|
570
|
+
const entries = await contextBranch(execution);
|
|
571
|
+
const pinned = await policyEntries(execution, state.pass > 1);
|
|
544
572
|
const messages = await canonical(execution, entries);
|
|
545
573
|
const delta = state.pass > 1 && previousSnapshot ? tailAfter(previousSnapshot, messages) : void 0;
|
|
546
|
-
const previous = state.pass > 1 ? require_compactionPolicy.checkpointSummaryFromEntry(require_compactionPolicy.latestCheckpointArtifactEntry(
|
|
574
|
+
const previous = state.pass > 1 ? require_compactionPolicy.checkpointSummaryFromEntry(require_compactionPolicy.latestCheckpointArtifactEntry(pinned)) : void 0;
|
|
547
575
|
const { reference, thinking } = await summaryModel(execution, configuration);
|
|
548
576
|
const instructions = checkpointInstructions(3, {
|
|
549
|
-
plan: latestPlanSnapshot(
|
|
577
|
+
plan: latestPlanSnapshot(pinned),
|
|
550
578
|
contextContributions: await contributionSnapshot(execution),
|
|
551
579
|
readFiles: state.readFiles,
|
|
552
580
|
modifiedFiles: state.modifiedFiles
|
|
@@ -588,14 +616,14 @@ function createNativeAutocompact(dependencies = {}) {
|
|
|
588
616
|
clear();
|
|
589
617
|
previousSnapshot = void 0;
|
|
590
618
|
};
|
|
591
|
-
const applyReady = async (execution, version) => {
|
|
619
|
+
const applyReady = async (execution, version, appendMessage) => {
|
|
592
620
|
if (state.phase !== "checkpoint_ready" || !state.pendingCheckpoint || !state.requestId || !state.snapshotLeafId) return false;
|
|
593
621
|
const decision = require_compactionPolicy.parseCheckpointDecision(state.pendingCheckpoint);
|
|
594
622
|
if (!require_compactionPolicy.isStructuredCheckpoint(decision.summary)) {
|
|
595
623
|
await fail(execution, version, /* @__PURE__ */ new Error("Summarization returned an incomplete checkpoint."), true);
|
|
596
624
|
return false;
|
|
597
625
|
}
|
|
598
|
-
const entries = await
|
|
626
|
+
const entries = await contextBranch(execution);
|
|
599
627
|
const messages = await canonical(execution, entries);
|
|
600
628
|
if (!alive(version)) return false;
|
|
601
629
|
const tail = snapshot && tailAfter(snapshot, messages);
|
|
@@ -621,7 +649,6 @@ function createNativeAutocompact(dependencies = {}) {
|
|
|
621
649
|
scheduleMirror(execution);
|
|
622
650
|
return false;
|
|
623
651
|
}
|
|
624
|
-
if (!execution.session.appendMessage) throw new Error("Checkpoint messages are unavailable.");
|
|
625
652
|
const files = require_compactionPolicy.mergeFileDetails(state, require_compactionPolicy.fileOperationsFromMessages(messages));
|
|
626
653
|
const details = {
|
|
627
654
|
...files,
|
|
@@ -637,16 +664,16 @@ function createNativeAutocompact(dependencies = {}) {
|
|
|
637
664
|
};
|
|
638
665
|
const idle = (await execution.session.activity()).isIdle;
|
|
639
666
|
if (!alive(version)) return false;
|
|
640
|
-
const id = await
|
|
667
|
+
const id = await appendMessage({
|
|
641
668
|
type: require_compactionPolicy.CONTEXT_MESSAGE_TYPE,
|
|
642
669
|
text: require_compactionPolicy.withCanonicalFileSections(decision.summary, files),
|
|
643
670
|
display: false,
|
|
644
671
|
details
|
|
645
|
-
});
|
|
672
|
+
}, { resetContext: { retainedMessages: tail } });
|
|
646
673
|
if (!alive(version) || !id) return false;
|
|
647
674
|
await execution.session.setLabel?.(id, `autocompact:c${state.cycle}:p${pass}`);
|
|
648
675
|
if (!alive(version)) return false;
|
|
649
|
-
const runtimeAttributes = await runtimeState(execution,
|
|
676
|
+
const runtimeAttributes = await runtimeState(execution, await policyEntries(execution, false), version, appendMessage);
|
|
650
677
|
if (!alive(version)) return false;
|
|
651
678
|
const committedAttributes = attributes();
|
|
652
679
|
state.readFiles = files.readFiles;
|
|
@@ -680,14 +707,7 @@ function createNativeAutocompact(dependencies = {}) {
|
|
|
680
707
|
const activity = await execution.session.activity();
|
|
681
708
|
if (!alive(version) || activity.hasPendingMessages) return;
|
|
682
709
|
if (appendMessage && (activity.isIdle || allowBusy)) {
|
|
683
|
-
|
|
684
|
-
...execution,
|
|
685
|
-
session: {
|
|
686
|
-
...execution.session,
|
|
687
|
-
appendMessage
|
|
688
|
-
}
|
|
689
|
-
};
|
|
690
|
-
if (await applyReady(checkpointExecution, version)) return;
|
|
710
|
+
if (await applyReady(execution, version, appendMessage)) return;
|
|
691
711
|
}
|
|
692
712
|
if (!alive(version) || state.phase !== "waiting") return;
|
|
693
713
|
const configuration = configured(execution);
|
|
@@ -713,17 +733,7 @@ function createNativeAutocompact(dependencies = {}) {
|
|
|
713
733
|
const pass = state.checkpointQueue[0];
|
|
714
734
|
if (!pass) return;
|
|
715
735
|
state.pass = pass;
|
|
716
|
-
const checkpointEntries =
|
|
717
|
-
type: "custom",
|
|
718
|
-
customType: PLAN_DOCUMENT_ENTRY,
|
|
719
|
-
limit: 1
|
|
720
|
-
})];
|
|
721
|
-
if (pass > 1) for await (const record of execution.session.entriesNewestFirst()) {
|
|
722
|
-
const entry = record;
|
|
723
|
-
if (!require_compactionPolicy.latestCheckpointArtifactEntry([entry])) continue;
|
|
724
|
-
checkpointEntries.push(entry);
|
|
725
|
-
break;
|
|
726
|
-
}
|
|
736
|
+
const checkpointEntries = await policyEntries(execution, pass > 1);
|
|
727
737
|
const messages = await canonical(execution, entries);
|
|
728
738
|
const steering = await contributionSnapshot(execution);
|
|
729
739
|
if (!alive(version)) return;
|
|
@@ -825,8 +835,7 @@ function createNativeAutocompact(dependencies = {}) {
|
|
|
825
835
|
snapshot = validMessages(data?.nativeSnapshot) ? data.nativeSnapshot : void 0;
|
|
826
836
|
previousSnapshot = validMessages(data?.nativePreviousSnapshot) ? data.nativePreviousSnapshot : void 0;
|
|
827
837
|
if (state.phase === "checkpoint_ready" && state.requestId) {
|
|
828
|
-
const
|
|
829
|
-
const artifacts = history.slice(entry ? history.findIndex((item) => item.id === entry.id) + 1 : 0);
|
|
838
|
+
const artifacts = await matching(execution, (item) => item.type === "custom" && item.customType === "po-autocompact-checkpoint" || require_compactionPolicy.customMessage(item)?.customType === "po-autocompact-context", entry?.id);
|
|
830
839
|
const committed = artifacts.findLast((item) => {
|
|
831
840
|
const message = item.type === "message" ? item.message : void 0;
|
|
832
841
|
if (message?.role !== "custom" || message.customType !== "po-autocompact-context") return false;
|