@agimon-ai/po-autocompact 0.0.0-alpha.113 → 0.0.0-alpha.114

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.
@@ -11,6 +11,7 @@ let _agimon_ai_po_core_contextContributions = require("@agimon-ai/po-core/contex
11
11
  let _agimon_ai_po_core_uiHub = require("@agimon-ai/po-core/uiHub");
12
12
  let _agimon_ai_po_config = require("@agimon-ai/po-config");
13
13
  let minimatch = require("minimatch");
14
+ //#endregion
14
15
  //#region src/services/autocompactTelemetry/index.ts
15
16
  const SERVICE_NAME = "po-autocompact";
16
17
  const PACKAGE_NAME = "@agimon-ai/po-autocompact";
@@ -162,18 +163,31 @@ const DEFAULT_RUNTIME_CONFIG = {
162
163
  ratios: {},
163
164
  overrides: []
164
165
  };
166
+ /** While admitted settings cannot be read a disable could be hidden, so autocompact stands down for the host. */
167
+ const UNAVAILABLE_RUNTIME_CONFIG = {
168
+ enabled: false,
169
+ ratios: {},
170
+ overrides: []
171
+ };
165
172
  /**
166
173
  * What the Po config says about this package.
167
174
  *
168
175
  * `modes.autocompact` is read first and `modes.planning.subagents` is the
169
176
  * fallback, because summarization borrowed the planning subagent model before
170
177
  * it had keys of its own and existing files still spell it that way.
178
+ *
179
+ * A host that admits its configuration passes `admitted`, and that is read instead of the files. Reading it
180
+ * failing is reported and stands autocompact down, where unreadable files keep the session model and stay on.
171
181
  */
172
- function autocompactRuntimeConfig(root, onLoadFailure) {
182
+ function autocompactRuntimeConfig(root, onLoadFailure, admitted) {
173
183
  let modes;
174
184
  try {
175
- modes = (0, _agimon_ai_po_config.loadPoConfig)(root).modes;
185
+ modes = admitted ? admitted() : (0, _agimon_ai_po_config.loadPoConfig)(root).modes;
176
186
  } catch (error) {
187
+ if (admitted) {
188
+ onLoadFailure?.(error);
189
+ return UNAVAILABLE_RUNTIME_CONFIG;
190
+ }
177
191
  process.emitWarning("Po autocompact configuration could not be loaded; using the active session model instead.");
178
192
  onLoadFailure?.(error);
179
193
  return DEFAULT_RUNTIME_CONFIG;
@@ -398,8 +412,12 @@ function createNativeAutocompact(dependencies = {}) {
398
412
  ...attributes(),
399
413
  "failure.kind": "configuration"
400
414
  });
415
+ if (dependencies.modes) Promise.allSettled([Promise.resolve().then(() => execution.client.notify({
416
+ body: `Po autocompact is paused until its configuration is available: ${error instanceof Error ? error.message : String(error)}`,
417
+ level: "warning"
418
+ }))]);
401
419
  }
402
- });
420
+ }, dependencies.modes);
403
421
  const alive = (version) => active && !navigating && generation === version;
404
422
  const refreshStatus = (execution) => {
405
423
  const phase = state.phase === "checkpoint_pending" ? "summarizing" : state.phase === "checkpoint_ready" ? "applying" : void 0;
@@ -1059,11 +1077,14 @@ function createNativeAutocompact(dependencies = {}) {
1059
1077
  }
1060
1078
  //#endregion
1061
1079
  //#region src/extensions/workspaces/sessions/(backend)/root.server.ts
1062
- var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(({ agent }) => {
1063
- const runtime = createNativeAutocompact({ telemetry: createAutocompactTelemetry({
1064
- env: agent?.context.environment,
1065
- cwd: agent?.context.cwd
1066
- }) });
1080
+ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(({ agent, context }) => {
1081
+ const runtime = createNativeAutocompact({
1082
+ telemetry: createAutocompactTelemetry({
1083
+ env: agent?.context.environment,
1084
+ cwd: agent?.context.cwd
1085
+ }),
1086
+ modes: void 0
1087
+ });
1067
1088
  return {
1068
1089
  value: runtime,
1069
1090
  services: [runtime.plugin],
@@ -1 +1 @@
1
- {"version":3,"file":"server.cjs","names":["createPoTelemetry","PO_CONTEXT_CONTRIBUTIONS_SERVICE","loadPoConfig","COMPACTION_ARTIFACT_DIRECTORY","customMessage","contextDetailsFromUnknown","checkpointSummaryFromEntry","openArtifact","ArtifactAccessError","readArtifactBytes","writeArtifactText","listArtifacts","removeArtifact","createInitialState","STATE_CUSTOM_TYPE","latestCheckpointArtifactEntry","customMessage","projectContextMessages","artifactRoot","RUNTIME_STATE_MESSAGE_TYPE","checkpointSummaryFromEntry","parseCheckpointDecision","isStructuredCheckpoint","mergeFileDetails","fileOperationsFromMessages","withCanonicalFileSections","CHECKPOINT_MESSAGE_TYPE","checkpointRequestDetails","CONTEXT_MESSAGE_TYPE","RESUME_MESSAGE_TYPE","effectiveThresholds","baselineUsageIsSettled","createRequestId","parseState","contextDetailsFromUnknown","fileDetailsFromUnknown","PO_UI_HUB_SERVICE","requirePoUiHub","PO_CONTEXT_CONTRIBUTIONS_SERVICE","requirePoContextContributions","defineRoot","defineHook","defineHook","defineHook","defineHook","defineHook","defineHook","defineHook","defineServerPlugin","composeServerProviderOverrides","rootSession","composeRootInjects","composeRootHooks","hookAgentSettled","hookContext","hookSessionBeforeCompact","hookSessionCompact","hookSessionStart","hookSessionTree","hookTurnEnd"],"sources":["../../src/services/autocompactTelemetry/index.ts","../../src/constants/runtime.ts","../../src/services/autocompactRuntime/index.ts","../../src/services/compactionHistory/index.ts","../../src/services/modelOverrides/index.ts","../../src/services/summarizationModel/index.ts","../../src/services/nativeAutocompact/index.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/context.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-before-compact.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-compact.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-start.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-tree.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/turn-end.server.ts","../../generated/server.ts"],"sourcesContent":["import {\n createPoTelemetry,\n type PoTelemetry,\n type PoTelemetryErrorOptions,\n type PoTelemetryOptions,\n} from '@agimon-ai/po-core/telemetry';\n\nconst SERVICE_NAME = 'po-autocompact';\nconst PACKAGE_NAME = '@agimon-ai/po-autocompact';\n\nexport const AUTOCOMPACT_EVENT = {\n checkpointStarted: 'po_autocompact.checkpoint_started',\n checkpointCompleted: 'po_autocompact.checkpoint_completed',\n checkpointFailed: 'po_autocompact.checkpoint_failed',\n checkpointInvalid: 'po_autocompact.checkpoint_invalid',\n configurationLoadFailed: 'po_autocompact.configuration_load_failed',\n contextContributionDegraded: 'po_autocompact.context_contribution_degraded',\n contextCommitted: 'po_autocompact.context_committed',\n contextApplied: 'po_autocompact.context_applied',\n contextMarkerInvalid: 'po_autocompact.context_marker_invalid',\n contextHookSlow: 'po_autocompact.context_hook_slow',\n nativeCompactionCompleted: 'po_autocompact.native_compaction_completed',\n historyWriteFailed: 'po_autocompact.history_write_failed',\n} as const;\n\nexport type AutocompactEventName = (typeof AUTOCOMPACT_EVENT)[keyof typeof AUTOCOMPACT_EVENT];\nexport type AutocompactEventAttributes = Record<string, string | number | boolean>;\n\nexport interface AutocompactTelemetryOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<PoTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n}\n\nexport interface AutocompactTelemetry {\n recordError(\n event: AutocompactEventName,\n error: unknown,\n attributes?: AutocompactEventAttributes,\n options?: PoTelemetryErrorOptions,\n ): Promise<void>;\n recordWarning(event: AutocompactEventName, error: unknown, attributes?: AutocompactEventAttributes): Promise<void>;\n recordEvent(event: AutocompactEventName, attributes?: AutocompactEventAttributes): Promise<void>;\n runInSpan<T>(name: string, attributes: AutocompactEventAttributes, callback: () => Promise<T>): Promise<T>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createAutocompactTelemetry(options: AutocompactTelemetryOptions = {}): AutocompactTelemetry {\n const telemetry: PoTelemetry = createPoTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n });\n return {\n recordError: (event, error, attributes, errorOptions) =>\n telemetry.recordError(event, error, attributes, errorOptions),\n recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),\n recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),\n runInSpan: (name, attributes, callback) => telemetry.runInSpan(name, attributes, callback),\n flush: () => telemetry.flush(),\n shutdown: () => telemetry.shutdown(),\n };\n}\n","export const ROOT_WORKING_LEAF = '@root';\nexport const PLAN_DOCUMENT_ENTRY = 'agent-harness-plan-document';\nexport const FOOTER_SOURCE = 'po-autocompact';\nexport const FOOTER_ORDER = 20;\nexport const STATUS_KEY = 'po-autocompact';\nexport const STATE_PHASE = {\n waiting: 'waiting',\n checkpointPending: 'checkpoint_pending',\n checkpointReady: 'checkpoint_ready',\n compacting: 'compacting',\n} as const;\n\n/**\n * Above this, the context hook is worth a telemetry event. Below it the hook is\n * noise against a round trip measured in seconds, and it runs on every request.\n */\nexport const SLOW_CONTEXT_HOOK_MS = 25;\n","import { loadPoConfig, type AutocompactOverrideConfig, type PlanningAgentConfig } from '@agimon-ai/po-config';\nimport {\n PO_CONTEXT_CONTRIBUTIONS_SERVICE,\n type PoContextContributionEntry,\n type PoContextContributionError,\n type PoContextContributionsService,\n type PoContextContributionsSnapshot,\n} from '@agimon-ai/po-core/contextContributions';\n\nimport { PLAN_DOCUMENT_ENTRY } from '../../constants/runtime';\nimport type { AutocompactPass, AutocompactRatioOverrides } from '../../types/autocompact';\nimport type { CompactionPolicyEntry } from '../compactionPolicy';\n\ninterface PlanSnapshot {\n content: string;\n path: string;\n}\n\ninterface SteeringSnapshot {\n plan?: PlanSnapshot;\n contextContributions: PoContextContributionsSnapshot;\n readFiles: string[];\n modifiedFiles: string[];\n}\n\ninterface RuntimeStateSnapshot {\n planPath?: string;\n contributions: readonly PoContextContributionEntry[];\n contributionErrors: readonly PoContextContributionError[];\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function latestPlanSnapshot(branch: readonly CompactionPolicyEntry[]): PlanSnapshot | undefined {\n for (const entry of branch.toReversed()) {\n if (entry.type !== 'custom' || entry.customType !== PLAN_DOCUMENT_ENTRY) continue;\n if (!entry.data || typeof entry.data !== 'object') return undefined;\n const data = entry.data as Record<string, unknown>;\n if (typeof data.content !== 'string' || typeof data.path !== 'string') return undefined;\n return { content: data.content, path: data.path };\n }\n return undefined;\n}\n\nconst EMPTY_CONTEXT_CONTRIBUTIONS: PoContextContributionsSnapshot = Object.freeze({\n entries: Object.freeze([]),\n errors: Object.freeze([]),\n});\n\nexport function readContextContributionsSnapshot(\n service: PoContextContributionsService | undefined,\n): PoContextContributionsSnapshot {\n if (!service) return EMPTY_CONTEXT_CONTRIBUTIONS;\n try {\n return service.snapshot();\n } catch (error) {\n return {\n entries: [],\n errors: [\n {\n source: PO_CONTEXT_CONTRIBUTIONS_SERVICE,\n id: 'service-snapshot',\n label: 'Context contributions',\n order: 0,\n message: errorMessage(error),\n },\n ],\n };\n }\n}\n\nfunction formatContextContributions(snapshot: PoContextContributionsSnapshot): string {\n const sections = snapshot.entries.map((entry) => `### ${entry.label}\\n${entry.text}`);\n sections.push(...snapshot.errors.map((error) => `### ${error.label}\\n(unavailable: ${error.message})`));\n return sections.length > 0 ? sections.join('\\n\\n') : '(no registered context contributions)';\n}\n\nexport function runtimeStateSnapshot(\n branch: readonly CompactionPolicyEntry[],\n contextContributions: PoContextContributionsSnapshot,\n): RuntimeStateSnapshot {\n const plan = latestPlanSnapshot(branch);\n return {\n ...(plan ? { planPath: plan.path } : {}),\n contributions: contextContributions.entries,\n contributionErrors: contextContributions.errors,\n };\n}\n\nexport function formatRuntimeState(snapshot: RuntimeStateSnapshot): string {\n const plan = snapshot.planPath\n ? `Source: ${snapshot.planPath}\\nExact plan content is restored separately by Po Plan.`\n : '(no active plan document)';\n return `<compaction-runtime-state>\nAuthoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.\n<active-plan>\n${plan}\n</active-plan>\n<context-contributions>\n${formatContextContributions({ entries: snapshot.contributions, errors: snapshot.contributionErrors })}\n</context-contributions>\n</compaction-runtime-state>`;\n}\n\nfunction steeringEnvelope(snapshot: SteeringSnapshot): string {\n const plan = snapshot.plan\n ? `Source: ${snapshot.plan.path}\\n\\n${snapshot.plan.content}`\n : '(no active plan document)';\n const importantContext = [\n snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(', ')}` : undefined,\n snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(', ')}` : undefined,\n ].filter((value): value is string => Boolean(value));\n\n return `<compaction-steering priority=\"user,plan,context-contributions,important-context,recent-messages\">\n<user-prompt source=\"conversation\">\nTreat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.\n</user-prompt>\n<active-plan>\n${plan}\n</active-plan>\n<context-contributions>\n${formatContextContributions(snapshot.contextContributions)}\n</context-contributions>\n<important-context>\n${importantContext.length > 0 ? importantContext.join('\\n') : '(none recorded outside the conversation)'}\n</important-context>\n</compaction-steering>`;\n}\n\nexport function checkpointInstructions(pass: AutocompactPass, steering: SteeringSnapshot): string {\n const decision =\n pass === 2\n ? 'Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.\\n\\n'\n : '';\n\n // Summarization is a tool-less single LLM call, so instructions describe only what to\n // produce. Directives aimed at an implementing agent leak into the checkpoint body.\n return `Create Po autocompact checkpoint pass ${pass}.\n\n${steeringEnvelope(steering)}\n\nApply the steering evidence in priority order. Do not invent plan or contributed runtime state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.\n\n${decision}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.\n\n## Goal\n## Constraints & Preferences\n## Progress\n### Done\n### In Progress\n### Blocked\n## Key Decisions\n## Next Steps\n## Critical Context`;\n}\n\ninterface AutocompactRuntimeConfig {\n /** Off leaves compaction to the host; unset is on. */\n enabled: boolean;\n /** The agent that writes the summaries, from autocompact's own keys or planning's. */\n agent?: PlanningAgentConfig;\n ratios: AutocompactRatioOverrides;\n /** Per-model absolute token checkpoints, tried in file order. */\n overrides: AutocompactOverrideConfig[];\n}\n\nconst DEFAULT_RUNTIME_CONFIG: AutocompactRuntimeConfig = { enabled: true, ratios: {}, overrides: [] };\n\n/**\n * What the Po config says about this package.\n *\n * `modes.autocompact` is read first and `modes.planning.subagents` is the\n * fallback, because summarization borrowed the planning subagent model before\n * it had keys of its own and existing files still spell it that way.\n */\nexport function autocompactRuntimeConfig(\n root: string,\n onLoadFailure?: (error: unknown) => void,\n): AutocompactRuntimeConfig {\n let modes: ReturnType<typeof loadPoConfig>['modes'];\n try {\n modes = loadPoConfig(root).modes;\n } catch (error) {\n process.emitWarning('Po autocompact configuration could not be loaded; using the active session model instead.');\n onLoadFailure?.(error);\n return DEFAULT_RUNTIME_CONFIG;\n }\n const configured = modes?.autocompact;\n const ownAgent: PlanningAgentConfig | undefined =\n configured && (configured.model !== undefined || configured.thinking !== undefined)\n ? {\n ...(configured.model ? { model: configured.model } : {}),\n ...(configured.thinking ? { thinking: configured.thinking } : {}),\n }\n : undefined;\n const agent = ownAgent ?? modes?.planning?.subagents;\n const thresholds = configured?.thresholds;\n return {\n enabled: configured?.enabled ?? true,\n ...(agent ? { agent } : {}),\n ratios: {\n ...(thresholds?.pass1 === undefined ? {} : { 1: thresholds.pass1 }),\n ...(thresholds?.pass2 === undefined ? {} : { 2: thresholds.pass2 }),\n ...(thresholds?.pass3 === undefined ? {} : { 3: thresholds.pass3 }),\n },\n overrides: configured?.overrides ?? [],\n };\n}\n","import {\n ArtifactAccessError,\n COMPACTION_ARTIFACT_DIRECTORY,\n listArtifacts,\n openArtifact,\n readArtifactBytes,\n removeArtifact,\n writeArtifactText,\n} from '@agimon-ai/po-artifact/artifactFiles';\n\nimport { CHECKPOINT_MESSAGE_TYPE, CONTEXT_MESSAGE_TYPE } from '../../constants/autocompact';\nimport {\n checkpointSummaryFromEntry,\n contextDetailsFromUnknown,\n customMessage,\n type CompactionPolicyEntry,\n} from '../compactionPolicy';\nimport type { CompactionHistoryFile } from './type';\n\nconst FORMAT = 'po-compaction/1';\nconst HEADER = `---\\nformat: ${JSON.stringify(FORMAT)}\\n`;\nconst HISTORY_PATH = new RegExp(\n `^${COMPACTION_ARTIFACT_DIRECTORY}/(?:epoch-\\\\d+/(?:summary|checkpoint-\\\\d+)|in-epoch/checkpoint-\\\\d+)\\\\.md$`,\n);\n// Native compaction wraps its summary this way (pi-durable dist/harness/compaction.js, po-core piMessages).\nconst NATIVE_PREFIX =\n 'The conversation history before this point was compacted into the following summary:\\n\\n<summary>\\n';\nconst NATIVE_SUFFIX = '\\n</summary>';\n\ntype HistoryFields = Record<string, string | number | undefined>;\n\nfunction historyFile(path: string, fields: HistoryFields, body: string): CompactionHistoryFile {\n const header = Object.entries({ format: FORMAT, ...fields }).flatMap(([key, value]) =>\n value === undefined ? [] : [`${key}: ${JSON.stringify(value)}`],\n );\n return { path: `${COMPACTION_ARTIFACT_DIRECTORY}/${path}`, text: `---\\n${header.join('\\n')}\\n---\\n\\n${body}\\n` };\n}\n\nfunction isoTime(value: string | number): string | undefined {\n const time = new Date(value);\n return Number.isFinite(time.getTime()) ? time.toISOString() : undefined;\n}\n\nfunction passOf(value: unknown): number | undefined {\n if (typeof value !== 'object' || value === null || !('pass' in value)) return undefined;\n return value.pass === 1 || value.pass === 2 || value.pass === 3 ? value.pass : undefined;\n}\n\nfunction committedFields(entry: CompactionPolicyEntry): { body: string; fields: HistoryFields } | undefined {\n if (entry.type === 'compaction') {\n const summary = entry.summary.trim();\n const body =\n summary.startsWith(NATIVE_PREFIX) && summary.endsWith(NATIVE_SUFFIX)\n ? summary.slice(NATIVE_PREFIX.length, -NATIVE_SUFFIX.length).trim()\n : summary;\n return {\n body,\n fields: { source: 'compact', tokensBefore: entry.tokensBefore > 0 ? entry.tokensBefore : undefined },\n };\n }\n const marker = customMessage(entry);\n const details = marker?.customType === CONTEXT_MESSAGE_TYPE ? contextDetailsFromUnknown(marker.details) : undefined;\n if (!details) return undefined;\n return {\n body: checkpointSummaryFromEntry(entry) ?? '',\n fields: {\n source: 'autocompact',\n pass: details.poAutocompact.pass,\n tokensBefore: details.poAutocompact.tokensBefore,\n },\n };\n}\n\n/** The only entries `wantedHistory` reads, so mirrors can scan history without keeping the rest. */\nexport function isHistoryEntry(entry: CompactionPolicyEntry): boolean {\n const type = customMessage(entry)?.customType;\n return (\n entry.type === 'compaction' ||\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n type === CHECKPOINT_MESSAGE_TYPE ||\n type === CONTEXT_MESSAGE_TYPE\n );\n}\n\n/** Number commits along the active branch so a rewind rewrites the same epoch folders. */\nexport function wantedHistory(entries: readonly CompactionPolicyEntry[]): CompactionHistoryFile[] {\n const files: CompactionHistoryFile[] = [];\n let staged: Array<{ entry: CompactionPolicyEntry; summary: string; pass: number | undefined }> = [];\n let epoch = 1;\n const checkpoints = (folder: string) =>\n staged.map(({ entry, summary, pass }, index) =>\n historyFile(\n `${folder}/checkpoint-${index + 1}.md`,\n {\n kind: 'checkpoint',\n epoch,\n checkpoint: index + 1,\n entryId: entry.id,\n source: 'autocompact',\n pass,\n timestamp: isoTime(entry.timestamp),\n },\n summary,\n ),\n );\n for (const entry of entries) {\n const marker = customMessage(entry);\n if (\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n marker?.customType === CHECKPOINT_MESSAGE_TYPE\n ) {\n const summary = checkpointSummaryFromEntry(entry);\n if (summary)\n staged.push({ entry, summary, pass: passOf(entry.type === 'custom' ? entry.data : marker?.details) });\n continue;\n }\n const committed = committedFields(entry);\n if (!committed) continue;\n files.push(\n ...checkpoints(`epoch-${epoch}`),\n historyFile(\n `epoch-${epoch}/summary.md`,\n { kind: 'summary', epoch, entryId: entry.id, ...committed.fields, timestamp: isoTime(entry.timestamp) },\n committed.body,\n ),\n );\n staged = [];\n epoch += 1;\n }\n files.push(...checkpoints('in-epoch'));\n return files;\n}\n\nasync function ownedHistory(root: string, path: string): Promise<boolean> {\n const file = await openArtifact(root, path).catch((error: unknown) => {\n // Gone since the listing: nothing left to prune.\n if (error instanceof ArtifactAccessError && error.status === 404) return undefined;\n throw error;\n });\n if (!file) return false;\n try {\n const bytes = await readArtifactBytes(file.handle, Math.min(file.stat.size, HEADER.length));\n return new TextDecoder().decode(bytes) === HEADER;\n } finally {\n await file.handle.close();\n }\n}\n\n/** Mirror history into the session artifact folder. Pruning touches only files carrying this mirror's header. */\nexport async function mirrorCompactionHistory(root: string, entries: readonly CompactionPolicyEntry[]): Promise<void> {\n const files = wantedHistory(entries);\n // ponytail: rewinding to before the first checkpoint keeps the old files; prune on empty if that ever misleads.\n if (files.length === 0) return;\n for (const file of files) await writeArtifactText(root, file.path, file.text);\n const listed = await listArtifacts(root);\n if (listed.error) throw new Error(listed.error);\n const wanted = new Set(files.map((file) => file.path));\n const stale = listed.items.filter((item) => HISTORY_PATH.test(item.path) && !wanted.has(item.path));\n for (const item of stale) if (await ownedHistory(root, item.path)) await removeArtifact(root, item.path);\n for (const folder of new Set(stale.map((item) => item.path.slice(0, item.path.lastIndexOf('/')))))\n await removeArtifact(root, folder);\n}\n","/**\n * Picks the absolute token checkpoints configured for the model a session is running.\n *\n * DESIGN PATTERNS:\n * - Pure decision function, so the matching rule is unit-testable without a session,\n * a config file or a filesystem\n * - First match in file order wins, so a reader resolves a model by reading down the\n * list rather than by working out which pattern is the most specific\n * - A model matching nothing returns no overrides at all, which leaves the ratio\n * ladder exactly as it behaves without this feature\n *\n * AVOID:\n * - Stripping a thinking suffix the way subagent model scope does. That matches\n * free-typed config strings; this matches a resolved `Model`, whose `id` carries\n * the level in a separate field and never in the id itself.\n * - Matching a bare pattern against `provider/id`. The glob wildcard does not cross\n * the separator, so the subject has to follow the pattern's own shape.\n */\n\nimport type { AutocompactOverrideConfig } from '@agimon-ai/po-config';\nimport { minimatch } from 'minimatch';\n\nimport type { AutocompactTokenOverrides } from '../../types/autocompact';\n\n/** The parts of a resolved model the rules match on. */\nexport interface AutocompactModelIdentity {\n id: string;\n provider: string;\n}\n\n/**\n * A pattern naming a provider is matched against `provider/id`, anything else\n * against the bare id. `*` does not cross `/`, so a bare pattern tested against a\n * qualified subject would never match and would read as a silently dead rule.\n */\nfunction matchesModelPattern(pattern: string, model: AutocompactModelIdentity): boolean {\n const subject = pattern.includes('/') ? `${model.provider}/${model.id}` : model.id;\n return minimatch(subject, pattern, { nocase: true });\n}\n\nexport function resolveModelTokenOverrides(\n model: AutocompactModelIdentity | undefined,\n overrides: readonly AutocompactOverrideConfig[],\n): AutocompactTokenOverrides {\n if (!model) return {};\n const matched = overrides.find((entry) => matchesModelPattern(entry.model, model));\n if (!matched) return {};\n const { pass1, pass2, pass3 } = matched.tokens;\n return {\n ...(pass1 === undefined ? {} : { 1: pass1 }),\n ...(pass2 === undefined ? {} : { 2: pass2 }),\n ...(pass3 === undefined ? {} : { 3: pass3 }),\n };\n}\n","import type { ExtensionContext } from '@earendil-works/pi-coding-agent';\n\nconst THINKING_SUFFIX_PATTERN = /:(off|minimal|low|medium|high|xhigh|max)$/;\n\nexport interface SummarizationModel {\n model: NonNullable<ExtensionContext['model']>;\n thinkingLevel?: NonNullable<ExtensionContext['thinkingLevel']>;\n}\n\nexport interface ModelReference {\n provider: string;\n modelId: string;\n thinking?: NonNullable<ExtensionContext['thinkingLevel']>;\n}\n\n/** Splits a `provider/model` reference, tolerating the optional thinking suffix. */\nexport function parseModelReference(reference: string): ModelReference | undefined {\n const trimmed = reference.trim();\n const thinking = THINKING_SUFFIX_PATTERN.exec(trimmed)?.[1] as SummarizationModel['thinkingLevel'];\n const identity = trimmed.replace(THINKING_SUFFIX_PATTERN, '');\n const separator = identity.indexOf('/');\n if (separator <= 0 || separator >= identity.length - 1) return undefined;\n return {\n provider: identity.slice(0, separator),\n modelId: identity.slice(separator + 1),\n ...(thinking ? { thinking } : {}),\n };\n}\n","import { artifactRoot } from '@agimon-ai/po-artifact/artifactFiles';\nimport {\n PO_CONTEXT_CONTRIBUTIONS_SERVICE,\n requirePoContextContributions,\n type PoContextContributionsService,\n} from '@agimon-ai/po-core/contextContributions';\nimport type { PoFooterContributionHandle } from '@agimon-ai/po-core/footer';\nimport type { PoHeadlessExecutionContext, PoHeadlessHook } from '@agimon-ai/po-core/headless';\nimport { PO_UI_HUB_SERVICE, requirePoUiHub } from '@agimon-ai/po-core/uiHub';\n\nimport {\n CHECKPOINT_MESSAGE_TYPE,\n CONTEXT_MESSAGE_TYPE,\n MAX_INVALID_CHECKPOINT_ATTEMPTS,\n RESUME_MESSAGE_TYPE,\n RUNTIME_STATE_MESSAGE_TYPE,\n STATE_CUSTOM_TYPE,\n STATE_VERSION,\n} from '../../constants/autocompact';\nimport {\n FOOTER_ORDER,\n FOOTER_SOURCE,\n PLAN_DOCUMENT_ENTRY,\n SLOW_CONTEXT_HOOK_MS,\n STATUS_KEY,\n} from '../../constants/runtime';\nimport type { AutocompactContextDetails, AutocompactMessage, AutocompactState } from '../../types/autocompact';\nimport {\n autocompactRuntimeConfig,\n checkpointInstructions,\n formatRuntimeState,\n latestPlanSnapshot,\n readContextContributionsSnapshot,\n runtimeStateSnapshot,\n} from '../autocompactRuntime';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from '../autocompactTelemetry';\nimport { isHistoryEntry, mirrorCompactionHistory } from '../compactionHistory';\nimport {\n baselineUsageIsSettled,\n checkpointRequestDetails,\n checkpointSummaryFromEntry,\n contextDetailsFromUnknown,\n createInitialState,\n createRequestId,\n customMessage,\n effectiveThresholds,\n fileDetailsFromUnknown,\n fileOperationsFromMessages,\n isStructuredCheckpoint,\n latestCheckpointArtifactEntry,\n mergeFileDetails,\n parseCheckpointDecision,\n parseState,\n projectContextMessages,\n withCanonicalFileSections,\n type CompactionPolicyEntry,\n} from '../compactionPolicy';\nimport { resolveModelTokenOverrides } from '../modelOverrides';\nimport { parseModelReference } from '../summarizationModel';\nimport type { NativeAutocompactDependencies, NativeAutocompactRuntime } from './type';\n\n/** Exact canonical-prefix comparison refuses to apply summaries to edited or replaced evidence. */\nfunction tailAfter(\n snapshot: readonly AutocompactMessage[],\n current: readonly AutocompactMessage[],\n): AutocompactMessage[] | undefined {\n if (\n snapshot.length > current.length ||\n snapshot.some((message, index) => JSON.stringify(message) !== JSON.stringify(current[index]))\n )\n return undefined;\n return current.slice(snapshot.length);\n}\n\nfunction leaf(entries: readonly CompactionPolicyEntry[]): string {\n return (\n entries.findLast(\n (entry) =>\n entry.type !== 'custom' ||\n (entry.customType !== STATE_CUSTOM_TYPE && entry.customType !== CHECKPOINT_MESSAGE_TYPE),\n )?.id ?? 'root'\n );\n}\n\nexport function createNativeAutocompact(dependencies: NativeAutocompactDependencies = {}): NativeAutocompactRuntime {\n const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();\n let active = true;\n let generation = 0;\n let state: AutocompactState = createInitialState();\n let snapshot: AutocompactMessage[] | undefined;\n let previousSnapshot: AutocompactMessage[] | undefined;\n let context: PoHeadlessExecutionContext | undefined;\n let contributions: PoContextContributionsService | undefined;\n let controller: AbortController | undefined;\n let serial: Promise<void> = Promise.resolve();\n const work = new Set<Promise<void>>();\n const applied = new Set<string>();\n const invalid = new Set<string>();\n let configFailureReported = false;\n let footer: PoFooterContributionHandle | undefined;\n let navigating = false;\n let degraded = false;\n let lastNativeCompactionId: string | undefined;\n let checkpointBoundary:\n | ReturnType<NonNullable<PoHeadlessExecutionContext['session']['registerCheckpointBoundary']>>\n | undefined;\n let mirrorQueued = false;\n let historyWarnedSession: string | undefined;\n\n const attributes = () => ({\n 'pi.session.id': context?.sessionId ?? '',\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': state.pass,\n ...(state.requestId ? { 'autocompact.request.id': state.requestId } : {}),\n ...(state.snapshotLeafId ? { 'autocompact.snapshot_leaf_id': state.snapshotLeafId } : {}),\n ...(state.snapshotTokens === undefined ? {} : { 'autocompact.tokens_before': state.snapshotTokens }),\n });\n const configured = (execution: PoHeadlessExecutionContext) =>\n autocompactRuntimeConfig(execution.repoRoot, (error) => {\n if (!configFailureReported) {\n configFailureReported = true;\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.configurationLoadFailed, error, {\n ...attributes(),\n 'failure.kind': 'configuration',\n });\n }\n });\n const alive = (version: number) => active && !navigating && generation === version;\n const refreshStatus = (execution: PoHeadlessExecutionContext) => {\n const phase =\n state.phase === 'checkpoint_pending'\n ? 'summarizing'\n : state.phase === 'checkpoint_ready'\n ? 'applying'\n : undefined;\n footer?.update(phase ? { fullText: `Compacting p${state.pass}`, compactText: `C${state.pass}` } : undefined);\n execution.client.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : undefined);\n };\n const enqueue = (callback: () => Promise<void>): Promise<void> => {\n const version = generation;\n const operation = serial.then(async () => {\n if (alive(version)) await callback();\n });\n serial = operation.catch(() => undefined);\n return operation;\n };\n const persist = async (execution: PoHeadlessExecutionContext, version: number) => {\n if (!alive(version)) return;\n await execution.session.appendCustomEntry(STATE_CUSTOM_TYPE, {\n ...state,\n nativeLastCompactionId: lastNativeCompactionId,\n });\n if (alive(version)) refreshStatus(execution);\n };\n const clear = () => {\n delete state.requestId;\n delete state.snapshotLeafId;\n delete state.snapshotTokens;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n snapshot = undefined;\n };\n const fail = async (\n execution: PoHeadlessExecutionContext,\n version: number,\n error: unknown,\n malformed = false,\n kind:\n | 'empty_checkpoint'\n | 'evidence_changed'\n | 'configuration'\n | 'persistence'\n | 'validation'\n | 'unknown' = 'unknown',\n ) => {\n if (!alive(version)) return;\n degraded = true;\n const eventAttributes = attributes();\n const attempts = state.invalidAttempts + 1;\n const pass = state.pass;\n const failedLeaf = state.snapshotLeafId;\n state.invalidAttempts += 1;\n if (state.invalidAttempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS) {\n state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);\n state.exhaustedPasses.push(pass);\n state.invalidAttempts = 0;\n }\n state.phase = 'waiting';\n clear();\n state.lastAttemptLeafId = failedLeaf;\n const errors = [error];\n try {\n await persist(execution, version);\n } catch (persistError) {\n errors.push(persistError);\n }\n if (!alive(version)) return;\n // Reporting is best effort: neither sink may prevent recovery or the native-compaction fallback.\n await Promise.allSettled([\n Promise.resolve().then(() =>\n execution.client.notify({\n body: `Po autocompact summarization pass ${pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n level: 'error',\n }),\n ),\n ...errors.map((failure, index) =>\n Promise.resolve().then(() =>\n telemetry.recordError(\n malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed,\n failure,\n {\n ...eventAttributes,\n 'failure.kind': index === 0 ? kind : 'persistence',\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS,\n },\n // The summarizer's failure is the only clue to why a pass failed; the sink redacts secrets.\n { includeException: true },\n ),\n ),\n ),\n ]);\n };\n // Stream history newest first, keeping only matching entries (oldest first), so large custom journals never pile up.\n const matching = async (\n execution: PoHeadlessExecutionContext,\n keep: (entry: CompactionPolicyEntry) => boolean,\n stopAt?: string,\n ) => {\n const entries: CompactionPolicyEntry[] = [];\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n if (entry.id === stopAt) break;\n if (keep(entry)) entries.push(entry);\n }\n return entries.reverse();\n };\n // Snapshot metadata can precede the context boundary: read only the newest plan and, when asked, checkpoint artifact.\n const policyEntries = async (execution: PoHeadlessExecutionContext, withCheckpoint: boolean) => {\n const entries = [\n ...(await execution.session.entries({\n type: 'custom',\n customType: PLAN_DOCUMENT_ENTRY,\n limit: 1,\n })),\n ] as unknown as CompactionPolicyEntry[];\n if (withCheckpoint) {\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n if (!latestCheckpointArtifactEntry([entry])) continue;\n entries.push(entry);\n break;\n }\n }\n return entries;\n };\n const contextBranch = async (execution: PoHeadlessExecutionContext) => {\n const entries: CompactionPolicyEntry[] = [];\n let foundLeaf = false;\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n const isLeaf = leaf([entry]) !== 'root';\n // Custom journals do not contribute model context. Keep only the newest leaf identity.\n if (entry.type !== 'custom' || (!foundLeaf && isLeaf)) entries.push(entry);\n if (isLeaf) foundLeaf = true;\n if (entry.type === 'compaction' || customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE) break;\n }\n return entries.reverse();\n };\n const canonical = async (execution: PoHeadlessExecutionContext, entries: CompactionPolicyEntry[]) => {\n if (!execution.session.contextMessages) throw new Error('Canonical context is unavailable for autocompact.');\n return projectContextMessages(\n (await execution.session.contextMessages()) as unknown as AutocompactMessage[],\n entries,\n ).messages;\n };\n // History is a convenience copy: its failure is reported once per session and never touches compaction state.\n // Never await this inside a queued job; it queues behind the job that schedules it.\n const scheduleMirror = (execution: PoHeadlessExecutionContext) => {\n if (mirrorQueued) return;\n mirrorQueued = true;\n void enqueue(async () => {\n mirrorQueued = false;\n try {\n await mirrorCompactionHistory(\n artifactRoot(execution.sessionId, execution.environment),\n await matching(execution, isHistoryEntry),\n );\n } catch (error) {\n const warn = historyWarnedSession !== execution.sessionId;\n historyWarnedSession = execution.sessionId;\n await Promise.allSettled([\n Promise.resolve().then(() =>\n telemetry.recordWarning(AUTOCOMPACT_EVENT.historyWriteFailed, error, attributes()),\n ),\n ...(warn\n ? [\n Promise.resolve().then(() =>\n execution.client.notify({\n body: `Po autocompact could not save compaction history: ${error instanceof Error ? error.message : String(error)}`,\n level: 'warning',\n }),\n ),\n ]\n : []),\n ]);\n }\n }).finally(() => {\n mirrorQueued = false;\n });\n };\n const contributionSnapshot = async (execution: PoHeadlessExecutionContext) => {\n const result = readContextContributionsSnapshot(contributions);\n for (const error of result.errors) {\n await execution.client.notify({\n body: `Po autocompact context contribution degraded (${error.source}/${error.id}): ${error.message}`,\n level: 'warning',\n });\n await telemetry.recordWarning(AUTOCOMPACT_EVENT.contextContributionDegraded, new Error(error.message), {\n ...attributes(),\n 'autocompact.context_contribution.source': error.source,\n 'autocompact.context_contribution.id': error.id,\n 'autocompact.context_contribution.order': error.order,\n });\n }\n return result;\n };\n const runtimeState = async (\n execution: PoHeadlessExecutionContext,\n entries: CompactionPolicyEntry[],\n version: number,\n appendMessage: PoHeadlessExecutionContext['session']['appendMessage'] = checkpointBoundary?.appendMessage.bind(\n checkpointBoundary,\n ),\n ) => {\n const saved = runtimeStateSnapshot(entries, await contributionSnapshot(execution));\n if (!alive(version)) return;\n await appendMessage?.({\n type: RUNTIME_STATE_MESSAGE_TYPE,\n text: formatRuntimeState(saved),\n display: false,\n details: { version: 2, ...saved },\n });\n return {\n 'autocompact.runtime.plan_present': Boolean(saved.planPath),\n 'autocompact.runtime.contribution_count': saved.contributions.length,\n 'autocompact.runtime.contribution_error_count': saved.contributionErrors.length,\n };\n };\n const summaryModel = async (execution: PoHeadlessExecutionContext, configuration: ReturnType<typeof configured>) => {\n const ownReference = configuration.agent?.model ? parseModelReference(configuration.agent.model) : undefined;\n const candidate = ownReference ? `${ownReference.provider}/${ownReference.modelId}` : undefined;\n const reference =\n candidate && execution.textCompletion!.available(candidate)\n ? candidate\n : execution.model\n ? `${execution.model.provider}/${execution.model.id}`\n : '';\n const thinking =\n configuration.agent?.thinking ??\n (reference === candidate ? ownReference?.thinking : undefined) ??\n (await execution.session.readModelSettings?.())?.thinkingLevel;\n return { reference, thinking };\n };\n // Manual compaction summarizes stored entries, which still hold everything this extension only projected away.\n // Commit a checkpoint now instead, folding what arrived since this cycle's staged summary the way pass 3 does.\n const manualCompaction = async (event: { instructions?: unknown }, execution: PoHeadlessExecutionContext) => {\n const configuration = configured(execution);\n if (!configuration.enabled || !execution.textCompletion?.summarize) return;\n try {\n const entries = await contextBranch(execution);\n const pinned = await policyEntries(execution, state.pass > 1);\n const messages = await canonical(execution, entries);\n const delta = state.pass > 1 && previousSnapshot ? tailAfter(previousSnapshot, messages) : undefined;\n const previous = state.pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(pinned)) : undefined;\n const { reference, thinking } = await summaryModel(execution, configuration);\n const instructions = checkpointInstructions(3, {\n plan: latestPlanSnapshot(pinned),\n contextContributions: await contributionSnapshot(execution),\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n });\n const { summary } = parseCheckpointDecision(\n await execution.textCompletion.summarize(reference, {\n messages: (delta ?? messages) as unknown as Record<string, unknown>[],\n instructions:\n typeof event.instructions === 'string' && event.instructions.trim()\n ? `${instructions}\\n\\n${event.instructions}`\n : instructions,\n ...(previous ? { previousSummary: previous } : {}),\n ...(thinking ? { thinkingLevel: thinking } : {}),\n ...(execution.signal ? { signal: execution.signal } : {}),\n }),\n );\n if (!isStructuredCheckpoint(summary)) throw new Error('Summarization returned an incomplete checkpoint.');\n const files = mergeFileDetails(state, fileOperationsFromMessages(messages));\n const usage = await execution.session.contextUsage?.();\n return {\n compaction: {\n summary: withCanonicalFileSections(summary, files),\n tokensBefore: usage?.tokens ?? 0,\n retainedTail: [],\n details: files,\n },\n };\n } catch (error) {\n // The host falls back to native compaction, whose own failure would hide this reason.\n await execution.client.notify({\n body: `Po autocompact manual compaction failed: ${error instanceof Error ? error.message : String(error)}`,\n level: 'error',\n });\n throw error;\n }\n };\n const resetCycle = () => {\n state.phase = 'waiting';\n state.checkpointQueue = [];\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n state.baselinePending = true;\n state.cycle += 1;\n state.pass = 1;\n delete state.lastAttemptLeafId;\n delete state.latestCheckpointSnapshotLeafId;\n clear();\n previousSnapshot = undefined;\n };\n const applyReady = async (\n execution: PoHeadlessExecutionContext,\n version: number,\n appendMessage: NonNullable<typeof checkpointBoundary>['appendMessage'],\n ): Promise<boolean> => {\n if (state.phase !== 'checkpoint_ready' || !state.pendingCheckpoint || !state.requestId || !state.snapshotLeafId)\n return false;\n const decision = parseCheckpointDecision(state.pendingCheckpoint);\n if (!isStructuredCheckpoint(decision.summary)) {\n await fail(execution, version, new Error('Summarization returned an incomplete checkpoint.'), true, 'validation');\n return false;\n }\n const entries = await contextBranch(execution);\n const messages = await canonical(execution, entries);\n if (!alive(version)) return false;\n // Persisted legacy pending summaries lack canonical evidence. Retry rather than fabricate a retained tail.\n const tail = snapshot && tailAfter(snapshot, messages);\n if (!tail) {\n await fail(\n execution,\n version,\n new Error('Canonical checkpoint evidence changed; summary must be regenerated.'),\n false,\n 'evidence_changed',\n );\n return false;\n }\n const pass = state.pass;\n if (pass === 1 || (pass === 2 && decision.shouldCompact !== true)) {\n await execution.session.appendCustomEntry(CHECKPOINT_MESSAGE_TYPE, {\n ...checkpointRequestDetails(state.cycle, pass, state.requestId),\n summary: decision.summary,\n });\n if (!alive(version)) return false;\n previousSnapshot = snapshot;\n state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;\n state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);\n state.pass = pass === 1 ? 2 : 3;\n state.phase = 'waiting';\n state.invalidAttempts = 0;\n clear();\n await persist(execution, version);\n scheduleMirror(execution);\n return false;\n }\n const files = mergeFileDetails(state, fileOperationsFromMessages(messages));\n const details: AutocompactContextDetails = {\n ...files,\n poAutocompact: {\n version: STATE_VERSION,\n cycle: state.cycle,\n pass,\n requestId: state.requestId,\n snapshotLeafId: state.snapshotLeafId,\n tokensBefore: state.snapshotTokens ?? 0,\n },\n retainedMessages: tail,\n };\n const idle = (await execution.session.activity()).isIdle;\n if (!alive(version)) return false;\n // The marker heads native context, so native compaction and context reads skip everything before it.\n const id = await appendMessage(\n {\n type: CONTEXT_MESSAGE_TYPE,\n text: withCanonicalFileSections(decision.summary, files),\n display: false,\n details,\n },\n { resetContext: { retainedMessages: tail as unknown as Record<string, unknown>[] } },\n );\n if (!alive(version) || !id) return false;\n await execution.session.setLabel?.(id, `autocompact:c${state.cycle}:p${pass}`);\n if (!alive(version)) return false;\n const runtimeAttributes = await runtimeState(\n execution,\n await policyEntries(execution, false),\n version,\n appendMessage,\n );\n if (!alive(version)) return false;\n const committedAttributes = attributes();\n state.readFiles = files.readFiles;\n state.modifiedFiles = files.modifiedFiles;\n resetCycle();\n await persist(execution, version);\n scheduleMirror(execution);\n if (!alive(version)) return false;\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextCommitted, {\n ...committedAttributes,\n 'autocompact.message_count.before': messages.length,\n 'autocompact.message_count.retained': tail.length,\n 'autocompact.apply_mode': idle ? 'idle' : 'turn_end',\n ...runtimeAttributes,\n });\n if (idle && alive(version))\n await execution.session.admitPrompt?.(\n \"Asynchronous compaction completed. Continue from the compacted checkpoint's immediate next action without repeating completed work.\",\n 'steer',\n undefined,\n `${RESUME_MESSAGE_TYPE}:${details.poAutocompact.requestId}`,\n );\n return true;\n };\n const ensureCheckpointBoundary = (execution: PoHeadlessExecutionContext) => {\n if (checkpointBoundary) return;\n if (!execution.session.registerCheckpointBoundary) throw new Error('Native checkpoint boundaries are unavailable.');\n checkpointBoundary = execution.session.registerCheckpointBoundary(async (boundary) => {\n if (!active || navigating || boundary.signal?.aborted) return;\n const current = context ?? execution;\n await enqueue(() =>\n boundary.signal?.aborted ? Promise.resolve() : progress(current, true, boundary.appendMessage.bind(boundary)),\n );\n });\n };\n const advance = async (\n execution: PoHeadlessExecutionContext,\n allowBusy = false,\n appendMessage = checkpointBoundary?.appendMessage.bind(checkpointBoundary),\n ) => {\n const version = generation;\n context = execution;\n const activity = await execution.session.activity();\n if (!alive(version) || activity.hasPendingMessages) return;\n if (appendMessage && (activity.isIdle || allowBusy)) {\n if (await applyReady(execution, version, appendMessage)) return;\n }\n if (!alive(version) || state.phase !== 'waiting') return;\n const configuration = configured(execution);\n if (!configuration.enabled || !execution.session.contextUsage || !execution.textCompletion?.summarize) return;\n const usage = await execution.session.contextUsage();\n if (\n !alive(version) ||\n !usage ||\n typeof usage.tokens !== 'number' ||\n !Number.isFinite(usage.tokens) ||\n usage.tokens < 0\n )\n return;\n const tokens = usage.tokens;\n const thresholds = effectiveThresholds(\n usage.contextWindow,\n state.baselineTokens,\n configuration.ratios,\n resolveModelTokenOverrides(execution.model, configuration.overrides),\n );\n if (\n !state.baselinePending &&\n !state.checkpointQueue.length &&\n !([1, 2, 3] as const).some(\n (pass) => pass >= state.pass && !state.exhaustedPasses.includes(pass) && tokens >= thresholds[pass],\n )\n )\n return;\n const entries = await contextBranch(execution);\n if (!alive(version)) return;\n if (state.baselinePending) {\n if (!baselineUsageIsSettled(entries)) return;\n state.baselineTokens = usage.tokens;\n state.baselinePending = false;\n await persist(execution, version);\n return;\n }\n const currentLeaf = leaf(entries);\n if (currentLeaf === state.lastAttemptLeafId) return;\n for (const pass of [1, 2, 3] as const) {\n if (\n pass >= state.pass &&\n !state.checkpointQueue.includes(pass) &&\n !state.exhaustedPasses.includes(pass) &&\n usage.tokens >= thresholds[pass]\n )\n state.checkpointQueue.push(pass);\n }\n const pass = state.checkpointQueue[0];\n if (!pass) return;\n state.pass = pass;\n const checkpointEntries = await policyEntries(execution, pass > 1);\n const messages = await canonical(execution, entries);\n const steering = await contributionSnapshot(execution);\n if (!alive(version)) return;\n snapshot = messages;\n const previous =\n pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(checkpointEntries)) : undefined;\n const requestId = createRequestId(execution.sessionId, state.cycle, pass, currentLeaf);\n state.phase = 'checkpoint_pending';\n state.requestId = requestId;\n state.snapshotLeafId = currentLeaf;\n state.snapshotTokens = usage.tokens;\n delete state.lastAttemptLeafId;\n delete state.pendingCheckpoint;\n await persist(execution, version);\n if (!alive(version)) return;\n degraded = false;\n controller?.abort();\n controller = new AbortController();\n const signal = controller.signal;\n const requestAttributes = { ...attributes(), 'autocompact.message_count.before': messages.length };\n const delta = previousSnapshot ? tailAfter(previousSnapshot, messages) : undefined;\n let failureKind: 'configuration' | 'unknown' | 'persistence' = 'configuration';\n const completion = telemetry\n .runInSpan('po_autocompact.checkpoint', requestAttributes, async () => {\n const { reference, thinking } = await summaryModel(execution, configuration);\n failureKind = 'unknown';\n if (!alive(version) || signal.aborted) return '';\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, requestAttributes);\n return execution.textCompletion!.summarize!(reference, {\n messages: (pass > 1 && delta ? delta : messages) as unknown as Record<string, unknown>[],\n instructions: checkpointInstructions(pass, {\n plan: latestPlanSnapshot(checkpointEntries),\n contextContributions: steering,\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n }),\n ...(previous ? { previousSummary: previous } : {}),\n ...(thinking ? { thinkingLevel: thinking } : {}),\n signal,\n });\n })\n .then(async (summary) => {\n await enqueue(async () => {\n if (!alive(version) || signal.aborted || state.requestId !== requestId) return;\n if (!summary.trim()) {\n await fail(\n execution,\n version,\n new Error('Summarization returned an empty checkpoint.'),\n false,\n 'empty_checkpoint',\n );\n return;\n }\n state.phase = 'checkpoint_ready';\n state.pendingCheckpoint = summary.trim();\n failureKind = 'persistence';\n await persist(execution, version);\n failureKind = 'unknown';\n if (!alive(version)) return;\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {\n ...requestAttributes,\n 'autocompact.checkpoint.characters': summary.length,\n });\n if ((await execution.session.activity()).isIdle && alive(version)) await progress(execution);\n });\n })\n .catch(async (error: unknown) => {\n await enqueue(async () => {\n if (alive(version) && state.requestId === requestId)\n await fail(execution, version, error, false, failureKind);\n });\n });\n work.add(completion);\n void completion.then(\n () => work.delete(completion),\n () => work.delete(completion),\n );\n };\n const progress = async (\n execution: PoHeadlessExecutionContext,\n allowBusy = false,\n appendMessage?: Parameters<typeof advance>[2],\n ) => {\n const version = generation;\n try {\n ensureCheckpointBoundary(execution);\n await advance(execution, allowBusy, appendMessage);\n } catch (error) {\n try {\n await fail(execution, version, error, false, 'persistence');\n } finally {\n // Infrastructure failures can recover without a new conversation leaf.\n if (alive(version)) delete state.lastAttemptLeafId;\n }\n }\n };\n const load = async (execution: PoHeadlessExecutionContext) => {\n if (!active) return;\n navigating = false;\n generation += 1;\n const version = generation;\n controller?.abort(new Error('Autocompact session generation changed.'));\n controller = undefined;\n context = execution;\n applied.clear();\n invalid.clear();\n const saved = await execution.session.customSnapshot?.(STATE_CUSTOM_TYPE);\n if (!alive(version)) return;\n const entry = (saved?.available ? saved.entry : undefined) as unknown as CompactionPolicyEntry | undefined;\n const data =\n entry?.type === 'custom' && entry.data && typeof entry.data === 'object'\n ? (entry.data as Record<string, unknown>)\n : undefined;\n state = parseState(data) ?? createInitialState();\n lastNativeCompactionId = typeof data?.nativeLastCompactionId === 'string' ? data.nativeLastCompactionId : undefined;\n const validMessages = (value: unknown): value is AutocompactMessage[] =>\n Array.isArray(value) &&\n value.every((message) => message && typeof message === 'object' && typeof message.role === 'string');\n snapshot = validMessages(data?.nativeSnapshot) ? data.nativeSnapshot : undefined;\n previousSnapshot = validMessages(data?.nativePreviousSnapshot) ? data.nativePreviousSnapshot : undefined;\n // A marker can commit before its following state entry. Recover only the exact\n // request after the saved state, rather than retrying against already-compacted evidence.\n if (entry?.id && state.phase === 'checkpoint_ready' && state.requestId) {\n const artifacts = await matching(\n execution,\n (item) =>\n (item.type === 'custom' && item.customType === CHECKPOINT_MESSAGE_TYPE) ||\n customMessage(item)?.customType === CONTEXT_MESSAGE_TYPE,\n entry?.id,\n );\n const committed = artifacts.findLast((item) => {\n const message = item.type === 'message' ? item.message : undefined;\n if (message?.role !== 'custom' || message.customType !== CONTEXT_MESSAGE_TYPE) return false;\n const details = contextDetailsFromUnknown(message.details);\n return (\n details !== undefined &&\n details.poAutocompact.requestId === state.requestId &&\n details.poAutocompact.cycle === state.cycle &&\n details.poAutocompact.pass === state.pass &&\n details.poAutocompact.snapshotLeafId === state.snapshotLeafId &&\n isStructuredCheckpoint(checkpointSummaryFromEntry(item) ?? '')\n );\n });\n if (committed?.type === 'message' && committed.message.role === 'custom') {\n const details = contextDetailsFromUnknown(committed.message.details)!;\n state.readFiles = details.readFiles;\n state.modifiedFiles = details.modifiedFiles;\n resetCycle();\n await persist(execution, version);\n } else {\n const staged = artifacts.findLast((item) => {\n if (item.type !== 'custom' || item.customType !== CHECKPOINT_MESSAGE_TYPE) return false;\n const details = item.data as Record<string, unknown> | undefined;\n return (\n details?.version === STATE_VERSION &&\n details.requestId === state.requestId &&\n details.cycle === state.cycle &&\n details.pass === state.pass &&\n isStructuredCheckpoint(checkpointSummaryFromEntry(item) ?? '')\n );\n });\n if (staged && (state.pass === 1 || state.pass === 2)) {\n previousSnapshot = snapshot;\n state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;\n state.checkpointQueue = state.checkpointQueue.filter((pass) => pass !== state.pass);\n state.pass = state.pass === 1 ? 2 : 3;\n state.phase = 'waiting';\n state.invalidAttempts = 0;\n clear();\n await persist(execution, version);\n }\n }\n }\n if (state.phase !== 'waiting' && (state.phase !== 'checkpoint_ready' || !snapshot)) {\n // ponytail: snapshot-free pending work regenerates after restart; durable prefix reconstruction can avoid this cost later.\n state.phase = 'waiting';\n clear();\n delete state.lastAttemptLeafId;\n await persist(execution, version);\n }\n if (!alive(version)) return;\n const progressed = enqueue(() => progress(execution));\n scheduleMirror(execution);\n await progressed;\n };\n const restore = async (execution: PoHeadlessExecutionContext) => {\n const version = generation + 1;\n try {\n await load(execution);\n } catch (error) {\n await fail(execution, version, error);\n }\n };\n const hooks: PoHeadlessHook[] = [\n { event: 'session_start', handle: (_event, execution) => restore(execution) },\n {\n event: 'session_tree',\n handle: (event, execution) => {\n if (!active) return;\n if (event.status === 'started') {\n navigating = true;\n generation += 1;\n controller?.abort(new Error('Autocompact navigation started.'));\n return;\n }\n return restore(execution);\n },\n },\n {\n event: 'turn_end',\n handle: (_event, execution) => enqueue(() => progress(execution)),\n },\n { event: 'agent_settled', handle: (_event, execution) => enqueue(() => progress(execution)) },\n {\n event: 'session_before_compact',\n handle: (event, execution) => {\n if (!active || navigating) return;\n if (event.reason === 'manual') return manualCompaction(event, execution);\n return !degraded &&\n configured(execution).enabled &&\n event.reason === 'threshold' &&\n (state.phase === 'checkpoint_pending' || state.phase === 'checkpoint_ready')\n ? { cancel: true }\n : undefined;\n },\n },\n {\n event: 'context',\n async handle(event, execution) {\n if (!active || navigating || !Array.isArray(event.messages)) return;\n const started = Date.now();\n try {\n const version = generation;\n const entries = await contextBranch(execution);\n if (!alive(version)) return;\n const projection = projectContextMessages(event.messages as AutocompactMessage[], entries);\n if (projection.invalidMarker) {\n const id = leaf(entries);\n if (!invalid.has(id)) {\n invalid.add(id);\n await telemetry.recordError(\n AUTOCOMPACT_EVENT.contextMarkerInvalid,\n new Error('Po autocompact context marker is malformed.'),\n { ...attributes(), 'autocompact.leaf_id': id },\n );\n }\n return;\n }\n if (!projection.marker) return;\n if (!applied.has(projection.marker.requestId)) {\n applied.add(projection.marker.requestId);\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextApplied, {\n ...attributes(),\n 'autocompact.request.id': projection.marker.requestId,\n 'autocompact.cycle': projection.marker.cycle,\n 'autocompact.pass': projection.marker.pass,\n 'autocompact.snapshot_leaf_id': projection.marker.snapshotLeafId,\n 'autocompact.tokens_before': projection.marker.tokensBefore,\n 'autocompact.message_count.before': event.messages.length,\n 'autocompact.message_count.after': projection.messages.length,\n 'autocompact.message_count.retained': projection.retainedMessageCount,\n });\n }\n return alive(version) ? { messages: projection.messages } : undefined;\n } finally {\n const hookMs = Date.now() - started;\n if (active && hookMs >= SLOW_CONTEXT_HOOK_MS)\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextHookSlow, {\n ...attributes(),\n hook_ms: hookMs,\n 'autocompact.message_count': event.messages.length,\n });\n }\n },\n },\n {\n event: 'session_compact',\n handle: (event, execution) => {\n if (\n !active ||\n event.status !== 'completed' ||\n typeof event.entryId !== 'string' ||\n event.entryId === lastNativeCompactionId\n )\n return;\n const observedGeneration = generation;\n return enqueue(async () => {\n const entries = (await execution.session.entries({\n type: 'compaction',\n limit: 1,\n })) as unknown as CompactionPolicyEntry[];\n const compacted = entries[0];\n if (\n !alive(observedGeneration) ||\n !compacted ||\n compacted.type !== 'compaction' ||\n compacted.id !== event.entryId ||\n compacted.id === lastNativeCompactionId\n )\n return;\n generation += 1;\n const version = generation;\n controller?.abort(new Error('Native compaction superseded checkpoint.'));\n controller = undefined;\n lastNativeCompactionId = compacted.id;\n const files = mergeFileDetails(\n state,\n undefined,\n fileDetailsFromUnknown('details' in compacted ? compacted.details : undefined),\n );\n state.readFiles = files.readFiles;\n state.modifiedFiles = files.modifiedFiles;\n await execution.session.setLabel?.(compacted.id, `autocompact:c${state.cycle}:external`);\n if (!alive(version)) return;\n const plan = (await execution.session.entries({\n type: 'custom',\n customType: PLAN_DOCUMENT_ENTRY,\n limit: 1,\n })) as unknown as CompactionPolicyEntry[];\n const runtimeAttributes = await runtimeState(execution, plan, version);\n if (!alive(version)) return;\n const nativeAttributes = attributes();\n resetCycle();\n await persist(execution, version);\n scheduleMirror(execution);\n if (alive(version))\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.nativeCompactionCompleted, {\n ...nativeAttributes,\n 'autocompact.native.reason': typeof event.reason === 'string' ? event.reason : 'unknown',\n 'autocompact.native.from_extension': 'fromHook' in compacted && compacted.fromHook === true,\n 'autocompact.tokens_before': compacted.tokensBefore,\n ...runtimeAttributes,\n });\n });\n },\n },\n ];\n return {\n hooks,\n plugin(cordis) {\n cordis.inject([PO_UI_HUB_SERVICE], (injected) => {\n const contribution = requirePoUiHub(injected).registerFooter({\n source: FOOTER_SOURCE,\n id: 'autocompact',\n order: FOOTER_ORDER,\n });\n footer = contribution;\n if (context && active) refreshStatus(context);\n return () => {\n contribution.dispose();\n if (footer === contribution) footer = undefined;\n };\n });\n cordis.inject([PO_CONTEXT_CONTRIBUTIONS_SERVICE], (injected) => {\n const service = requirePoContextContributions(injected);\n contributions = service;\n return () => {\n if (contributions === service) contributions = undefined;\n };\n });\n },\n start: restore,\n async stop() {\n active = false;\n checkpointBoundary?.dispose();\n checkpointBoundary = undefined;\n generation += 1;\n controller?.abort(new Error('Autocompact is shutting down.'));\n await Promise.allSettled([...work, serial]);\n context?.client.setStatus(STATUS_KEY, undefined);\n footer?.update(undefined);\n footer = undefined;\n context = undefined;\n contributions = undefined;\n await telemetry.shutdown();\n },\n };\n}\n","import { defineRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createAutocompactTelemetry } from '../../../../services/autocompactTelemetry';\nimport { createNativeAutocompact } from '../../../../services/nativeAutocompact';\n\nexport default defineRoot(({ agent }: PoServerPluginContext) => {\n const runtime = createNativeAutocompact({\n telemetry: createAutocompactTelemetry({ env: agent?.context.environment, cwd: agent?.context.cwd }),\n });\n return { value: runtime, services: [runtime.plugin], onDispose: runtime.stop };\n});\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'agent_settled')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'context')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_before_compact')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_compact')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_start')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_tree')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'turn_end')!,\n);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport hookAgentSettled from '../src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server';\nimport hookContext from '../src/extensions/workspaces/sessions/(backend)/hook/context.server';\nimport hookSessionBeforeCompact from '../src/extensions/workspaces/sessions/(backend)/hook/session-before-compact.server';\nimport hookSessionCompact from '../src/extensions/workspaces/sessions/(backend)/hook/session-compact.server';\nimport hookSessionStart from '../src/extensions/workspaces/sessions/(backend)/hook/session-start.server';\nimport hookSessionTree from '../src/extensions/workspaces/sessions/(backend)/hook/session-tree.server';\nimport hookTurnEnd from '../src/extensions/workspaces/sessions/(backend)/hook/turn-end.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-autocompact',\n providerOverrides: composeServerProviderOverrides(rootSession),\n injects: composeRootInjects({ session: [rootSession] }),\n session: async (context) => {\n const scopeSession = await context.scopeRoot('session', rootSession, context);\n const contextSession = { ...context, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeSession),\n get hooks(): PoServerSessionPlugin['hooks'] { return [via({ event: 'agent_settled' }, at(hookAgentSettled, contextSession)), via({ event: 'context' }, at(hookContext, contextSession)), via({ event: 'session_before_compact' }, at(hookSessionBeforeCompact, contextSession)), via({ event: 'session_compact' }, at(hookSessionCompact, contextSession)), via({ event: 'session_start' }, at(hookSessionStart, contextSession)), via({ event: 'session_tree' }, at(hookSessionTree, contextSession)), via({ event: 'turn_end' }, at(hookTurnEnd, contextSession))]; },\n services: [...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;;;;;;;AAOA,MAAM,eAAe;AACrB,MAAM,eAAe;AAErB,MAAa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GAAG,GAAGC,uCAA0B,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,kBAAkB,GAAG,GAAGC,gCAAoB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,8BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,eAAe,GAAG,GAAGC,6BAAiB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,WAAW,GAAG,GAAGC,yBAAa,cAAc,CAAC;IAAC;GAAG;GACtiB,UAAU,CAAC,GAAI,aAAa,YAAY,CAAC,CAAE;GAC3C,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EACvG;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"server.cjs","names":["createPoTelemetry","PO_CONTEXT_CONTRIBUTIONS_SERVICE","loadPoConfig","COMPACTION_ARTIFACT_DIRECTORY","customMessage","contextDetailsFromUnknown","checkpointSummaryFromEntry","openArtifact","ArtifactAccessError","readArtifactBytes","writeArtifactText","listArtifacts","removeArtifact","createInitialState","STATE_CUSTOM_TYPE","latestCheckpointArtifactEntry","customMessage","projectContextMessages","artifactRoot","RUNTIME_STATE_MESSAGE_TYPE","checkpointSummaryFromEntry","parseCheckpointDecision","isStructuredCheckpoint","mergeFileDetails","fileOperationsFromMessages","withCanonicalFileSections","CHECKPOINT_MESSAGE_TYPE","checkpointRequestDetails","CONTEXT_MESSAGE_TYPE","RESUME_MESSAGE_TYPE","effectiveThresholds","baselineUsageIsSettled","createRequestId","parseState","contextDetailsFromUnknown","fileDetailsFromUnknown","PO_UI_HUB_SERVICE","requirePoUiHub","PO_CONTEXT_CONTRIBUTIONS_SERVICE","requirePoContextContributions","defineRoot","defineHook","defineHook","defineHook","defineHook","defineHook","defineHook","defineHook","defineServerPlugin","composeServerProviderOverrides","rootSession","composeRootInjects","composeRootHooks","hookAgentSettled","hookContext","hookSessionBeforeCompact","hookSessionCompact","hookSessionStart","hookSessionTree","hookTurnEnd"],"sources":["../../src/services/admittedModes/index.ts","../../src/services/autocompactTelemetry/index.ts","../../src/constants/runtime.ts","../../src/services/autocompactRuntime/index.ts","../../src/services/compactionHistory/index.ts","../../src/services/modelOverrides/index.ts","../../src/services/summarizationModel/index.ts","../../src/services/nativeAutocompact/index.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/context.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-before-compact.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-compact.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-start.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-tree.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/turn-end.server.ts","../../generated/server.ts"],"sourcesContent":["import type { Context } from '@deepseek-ai/cordis';\n\nimport type { AdmittedModes } from './type';\n\n/**\n * Node reads the Po config files itself, afresh on every hook, so it admits nothing here.\n * The edge build replaces this module with `index.edge.ts`, which reads the host-admitted snapshot.\n */\nexport function admittedModes(_context: Context): AdmittedModes | undefined {\n return undefined;\n}\n","import {\n createPoTelemetry,\n type PoTelemetry,\n type PoTelemetryErrorOptions,\n type PoTelemetryOptions,\n} from '@agimon-ai/po-core/telemetry';\n\nconst SERVICE_NAME = 'po-autocompact';\nconst PACKAGE_NAME = '@agimon-ai/po-autocompact';\n\nexport const AUTOCOMPACT_EVENT = {\n checkpointStarted: 'po_autocompact.checkpoint_started',\n checkpointCompleted: 'po_autocompact.checkpoint_completed',\n checkpointFailed: 'po_autocompact.checkpoint_failed',\n checkpointInvalid: 'po_autocompact.checkpoint_invalid',\n configurationLoadFailed: 'po_autocompact.configuration_load_failed',\n contextContributionDegraded: 'po_autocompact.context_contribution_degraded',\n contextCommitted: 'po_autocompact.context_committed',\n contextApplied: 'po_autocompact.context_applied',\n contextMarkerInvalid: 'po_autocompact.context_marker_invalid',\n contextHookSlow: 'po_autocompact.context_hook_slow',\n nativeCompactionCompleted: 'po_autocompact.native_compaction_completed',\n historyWriteFailed: 'po_autocompact.history_write_failed',\n} as const;\n\nexport type AutocompactEventName = (typeof AUTOCOMPACT_EVENT)[keyof typeof AUTOCOMPACT_EVENT];\nexport type AutocompactEventAttributes = Record<string, string | number | boolean>;\n\nexport interface AutocompactTelemetryOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<PoTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n}\n\nexport interface AutocompactTelemetry {\n recordError(\n event: AutocompactEventName,\n error: unknown,\n attributes?: AutocompactEventAttributes,\n options?: PoTelemetryErrorOptions,\n ): Promise<void>;\n recordWarning(event: AutocompactEventName, error: unknown, attributes?: AutocompactEventAttributes): Promise<void>;\n recordEvent(event: AutocompactEventName, attributes?: AutocompactEventAttributes): Promise<void>;\n runInSpan<T>(name: string, attributes: AutocompactEventAttributes, callback: () => Promise<T>): Promise<T>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createAutocompactTelemetry(options: AutocompactTelemetryOptions = {}): AutocompactTelemetry {\n const telemetry: PoTelemetry = createPoTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n });\n return {\n recordError: (event, error, attributes, errorOptions) =>\n telemetry.recordError(event, error, attributes, errorOptions),\n recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),\n recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),\n runInSpan: (name, attributes, callback) => telemetry.runInSpan(name, attributes, callback),\n flush: () => telemetry.flush(),\n shutdown: () => telemetry.shutdown(),\n };\n}\n","export const ROOT_WORKING_LEAF = '@root';\nexport const PLAN_DOCUMENT_ENTRY = 'agent-harness-plan-document';\nexport const FOOTER_SOURCE = 'po-autocompact';\nexport const FOOTER_ORDER = 20;\nexport const STATUS_KEY = 'po-autocompact';\nexport const STATE_PHASE = {\n waiting: 'waiting',\n checkpointPending: 'checkpoint_pending',\n checkpointReady: 'checkpoint_ready',\n compacting: 'compacting',\n} as const;\n\n/**\n * Above this, the context hook is worth a telemetry event. Below it the hook is\n * noise against a round trip measured in seconds, and it runs on every request.\n */\nexport const SLOW_CONTEXT_HOOK_MS = 25;\n","import { loadPoConfig, type AutocompactOverrideConfig, type PlanningAgentConfig } from '@agimon-ai/po-config';\nimport {\n PO_CONTEXT_CONTRIBUTIONS_SERVICE,\n type PoContextContributionEntry,\n type PoContextContributionError,\n type PoContextContributionsService,\n type PoContextContributionsSnapshot,\n} from '@agimon-ai/po-core/contextContributions';\n\nimport { PLAN_DOCUMENT_ENTRY } from '../../constants/runtime';\nimport type { AutocompactPass, AutocompactRatioOverrides } from '../../types/autocompact';\nimport type { AdmittedModes, AutocompactModes } from '../admittedModes/type';\nimport type { CompactionPolicyEntry } from '../compactionPolicy';\n\ninterface PlanSnapshot {\n content: string;\n path: string;\n}\n\ninterface SteeringSnapshot {\n plan?: PlanSnapshot;\n contextContributions: PoContextContributionsSnapshot;\n readFiles: string[];\n modifiedFiles: string[];\n}\n\ninterface RuntimeStateSnapshot {\n planPath?: string;\n contributions: readonly PoContextContributionEntry[];\n contributionErrors: readonly PoContextContributionError[];\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function latestPlanSnapshot(branch: readonly CompactionPolicyEntry[]): PlanSnapshot | undefined {\n for (const entry of branch.toReversed()) {\n if (entry.type !== 'custom' || entry.customType !== PLAN_DOCUMENT_ENTRY) continue;\n if (!entry.data || typeof entry.data !== 'object') return undefined;\n const data = entry.data as Record<string, unknown>;\n if (typeof data.content !== 'string' || typeof data.path !== 'string') return undefined;\n return { content: data.content, path: data.path };\n }\n return undefined;\n}\n\nconst EMPTY_CONTEXT_CONTRIBUTIONS: PoContextContributionsSnapshot = Object.freeze({\n entries: Object.freeze([]),\n errors: Object.freeze([]),\n});\n\nexport function readContextContributionsSnapshot(\n service: PoContextContributionsService | undefined,\n): PoContextContributionsSnapshot {\n if (!service) return EMPTY_CONTEXT_CONTRIBUTIONS;\n try {\n return service.snapshot();\n } catch (error) {\n return {\n entries: [],\n errors: [\n {\n source: PO_CONTEXT_CONTRIBUTIONS_SERVICE,\n id: 'service-snapshot',\n label: 'Context contributions',\n order: 0,\n message: errorMessage(error),\n },\n ],\n };\n }\n}\n\nfunction formatContextContributions(snapshot: PoContextContributionsSnapshot): string {\n const sections = snapshot.entries.map((entry) => `### ${entry.label}\\n${entry.text}`);\n sections.push(...snapshot.errors.map((error) => `### ${error.label}\\n(unavailable: ${error.message})`));\n return sections.length > 0 ? sections.join('\\n\\n') : '(no registered context contributions)';\n}\n\nexport function runtimeStateSnapshot(\n branch: readonly CompactionPolicyEntry[],\n contextContributions: PoContextContributionsSnapshot,\n): RuntimeStateSnapshot {\n const plan = latestPlanSnapshot(branch);\n return {\n ...(plan ? { planPath: plan.path } : {}),\n contributions: contextContributions.entries,\n contributionErrors: contextContributions.errors,\n };\n}\n\nexport function formatRuntimeState(snapshot: RuntimeStateSnapshot): string {\n const plan = snapshot.planPath\n ? `Source: ${snapshot.planPath}\\nExact plan content is restored separately by Po Plan.`\n : '(no active plan document)';\n return `<compaction-runtime-state>\nAuthoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.\n<active-plan>\n${plan}\n</active-plan>\n<context-contributions>\n${formatContextContributions({ entries: snapshot.contributions, errors: snapshot.contributionErrors })}\n</context-contributions>\n</compaction-runtime-state>`;\n}\n\nfunction steeringEnvelope(snapshot: SteeringSnapshot): string {\n const plan = snapshot.plan\n ? `Source: ${snapshot.plan.path}\\n\\n${snapshot.plan.content}`\n : '(no active plan document)';\n const importantContext = [\n snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(', ')}` : undefined,\n snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(', ')}` : undefined,\n ].filter((value): value is string => Boolean(value));\n\n return `<compaction-steering priority=\"user,plan,context-contributions,important-context,recent-messages\">\n<user-prompt source=\"conversation\">\nTreat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.\n</user-prompt>\n<active-plan>\n${plan}\n</active-plan>\n<context-contributions>\n${formatContextContributions(snapshot.contextContributions)}\n</context-contributions>\n<important-context>\n${importantContext.length > 0 ? importantContext.join('\\n') : '(none recorded outside the conversation)'}\n</important-context>\n</compaction-steering>`;\n}\n\nexport function checkpointInstructions(pass: AutocompactPass, steering: SteeringSnapshot): string {\n const decision =\n pass === 2\n ? 'Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.\\n\\n'\n : '';\n\n // Summarization is a tool-less single LLM call, so instructions describe only what to\n // produce. Directives aimed at an implementing agent leak into the checkpoint body.\n return `Create Po autocompact checkpoint pass ${pass}.\n\n${steeringEnvelope(steering)}\n\nApply the steering evidence in priority order. Do not invent plan or contributed runtime state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.\n\n${decision}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.\n\n## Goal\n## Constraints & Preferences\n## Progress\n### Done\n### In Progress\n### Blocked\n## Key Decisions\n## Next Steps\n## Critical Context`;\n}\n\ninterface AutocompactRuntimeConfig {\n /** Off leaves compaction to the host; unset is on. */\n enabled: boolean;\n /** The agent that writes the summaries, from autocompact's own keys or planning's. */\n agent?: PlanningAgentConfig;\n ratios: AutocompactRatioOverrides;\n /** Per-model absolute token checkpoints, tried in file order. */\n overrides: readonly AutocompactOverrideConfig[];\n}\n\nconst DEFAULT_RUNTIME_CONFIG: AutocompactRuntimeConfig = { enabled: true, ratios: {}, overrides: [] };\n\n/** While admitted settings cannot be read a disable could be hidden, so autocompact stands down for the host. */\nconst UNAVAILABLE_RUNTIME_CONFIG: AutocompactRuntimeConfig = { enabled: false, ratios: {}, overrides: [] };\n\n/**\n * What the Po config says about this package.\n *\n * `modes.autocompact` is read first and `modes.planning.subagents` is the\n * fallback, because summarization borrowed the planning subagent model before\n * it had keys of its own and existing files still spell it that way.\n *\n * A host that admits its configuration passes `admitted`, and that is read instead of the files. Reading it\n * failing is reported and stands autocompact down, where unreadable files keep the session model and stay on.\n */\nexport function autocompactRuntimeConfig(\n root: string,\n onLoadFailure?: (error: unknown) => void,\n admitted?: AdmittedModes,\n): AutocompactRuntimeConfig {\n let modes: AutocompactModes | undefined;\n try {\n modes = admitted ? admitted() : loadPoConfig(root).modes;\n } catch (error) {\n if (admitted) {\n onLoadFailure?.(error);\n return UNAVAILABLE_RUNTIME_CONFIG;\n }\n process.emitWarning('Po autocompact configuration could not be loaded; using the active session model instead.');\n onLoadFailure?.(error);\n return DEFAULT_RUNTIME_CONFIG;\n }\n const configured = modes?.autocompact;\n const ownAgent: PlanningAgentConfig | undefined =\n configured && (configured.model !== undefined || configured.thinking !== undefined)\n ? {\n ...(configured.model ? { model: configured.model } : {}),\n ...(configured.thinking ? { thinking: configured.thinking } : {}),\n }\n : undefined;\n const agent = ownAgent ?? modes?.planning?.subagents;\n const thresholds = configured?.thresholds;\n return {\n enabled: configured?.enabled ?? true,\n ...(agent ? { agent } : {}),\n ratios: {\n ...(thresholds?.pass1 === undefined ? {} : { 1: thresholds.pass1 }),\n ...(thresholds?.pass2 === undefined ? {} : { 2: thresholds.pass2 }),\n ...(thresholds?.pass3 === undefined ? {} : { 3: thresholds.pass3 }),\n },\n overrides: configured?.overrides ?? [],\n };\n}\n","import {\n ArtifactAccessError,\n COMPACTION_ARTIFACT_DIRECTORY,\n listArtifacts,\n openArtifact,\n readArtifactBytes,\n removeArtifact,\n writeArtifactText,\n} from '@agimon-ai/po-artifact/artifactFiles';\n\nimport { CHECKPOINT_MESSAGE_TYPE, CONTEXT_MESSAGE_TYPE } from '../../constants/autocompact';\nimport {\n checkpointSummaryFromEntry,\n contextDetailsFromUnknown,\n customMessage,\n type CompactionPolicyEntry,\n} from '../compactionPolicy';\nimport type { CompactionHistoryFile } from './type';\n\nconst FORMAT = 'po-compaction/1';\nconst HEADER = `---\\nformat: ${JSON.stringify(FORMAT)}\\n`;\nconst HISTORY_PATH = new RegExp(\n `^${COMPACTION_ARTIFACT_DIRECTORY}/(?:epoch-\\\\d+/(?:summary|checkpoint-\\\\d+)|in-epoch/checkpoint-\\\\d+)\\\\.md$`,\n);\n// Native compaction wraps its summary this way (pi-durable dist/harness/compaction.js, po-core piMessages).\nconst NATIVE_PREFIX =\n 'The conversation history before this point was compacted into the following summary:\\n\\n<summary>\\n';\nconst NATIVE_SUFFIX = '\\n</summary>';\n\ntype HistoryFields = Record<string, string | number | undefined>;\n\nfunction historyFile(path: string, fields: HistoryFields, body: string): CompactionHistoryFile {\n const header = Object.entries({ format: FORMAT, ...fields }).flatMap(([key, value]) =>\n value === undefined ? [] : [`${key}: ${JSON.stringify(value)}`],\n );\n return { path: `${COMPACTION_ARTIFACT_DIRECTORY}/${path}`, text: `---\\n${header.join('\\n')}\\n---\\n\\n${body}\\n` };\n}\n\nfunction isoTime(value: string | number): string | undefined {\n const time = new Date(value);\n return Number.isFinite(time.getTime()) ? time.toISOString() : undefined;\n}\n\nfunction passOf(value: unknown): number | undefined {\n if (typeof value !== 'object' || value === null || !('pass' in value)) return undefined;\n return value.pass === 1 || value.pass === 2 || value.pass === 3 ? value.pass : undefined;\n}\n\nfunction committedFields(entry: CompactionPolicyEntry): { body: string; fields: HistoryFields } | undefined {\n if (entry.type === 'compaction') {\n const summary = entry.summary.trim();\n const body =\n summary.startsWith(NATIVE_PREFIX) && summary.endsWith(NATIVE_SUFFIX)\n ? summary.slice(NATIVE_PREFIX.length, -NATIVE_SUFFIX.length).trim()\n : summary;\n return {\n body,\n fields: { source: 'compact', tokensBefore: entry.tokensBefore > 0 ? entry.tokensBefore : undefined },\n };\n }\n const marker = customMessage(entry);\n const details = marker?.customType === CONTEXT_MESSAGE_TYPE ? contextDetailsFromUnknown(marker.details) : undefined;\n if (!details) return undefined;\n return {\n body: checkpointSummaryFromEntry(entry) ?? '',\n fields: {\n source: 'autocompact',\n pass: details.poAutocompact.pass,\n tokensBefore: details.poAutocompact.tokensBefore,\n },\n };\n}\n\n/** The only entries `wantedHistory` reads, so mirrors can scan history without keeping the rest. */\nexport function isHistoryEntry(entry: CompactionPolicyEntry): boolean {\n const type = customMessage(entry)?.customType;\n return (\n entry.type === 'compaction' ||\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n type === CHECKPOINT_MESSAGE_TYPE ||\n type === CONTEXT_MESSAGE_TYPE\n );\n}\n\n/** Number commits along the active branch so a rewind rewrites the same epoch folders. */\nexport function wantedHistory(entries: readonly CompactionPolicyEntry[]): CompactionHistoryFile[] {\n const files: CompactionHistoryFile[] = [];\n let staged: Array<{ entry: CompactionPolicyEntry; summary: string; pass: number | undefined }> = [];\n let epoch = 1;\n const checkpoints = (folder: string) =>\n staged.map(({ entry, summary, pass }, index) =>\n historyFile(\n `${folder}/checkpoint-${index + 1}.md`,\n {\n kind: 'checkpoint',\n epoch,\n checkpoint: index + 1,\n entryId: entry.id,\n source: 'autocompact',\n pass,\n timestamp: isoTime(entry.timestamp),\n },\n summary,\n ),\n );\n for (const entry of entries) {\n const marker = customMessage(entry);\n if (\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n marker?.customType === CHECKPOINT_MESSAGE_TYPE\n ) {\n const summary = checkpointSummaryFromEntry(entry);\n if (summary)\n staged.push({ entry, summary, pass: passOf(entry.type === 'custom' ? entry.data : marker?.details) });\n continue;\n }\n const committed = committedFields(entry);\n if (!committed) continue;\n files.push(\n ...checkpoints(`epoch-${epoch}`),\n historyFile(\n `epoch-${epoch}/summary.md`,\n { kind: 'summary', epoch, entryId: entry.id, ...committed.fields, timestamp: isoTime(entry.timestamp) },\n committed.body,\n ),\n );\n staged = [];\n epoch += 1;\n }\n files.push(...checkpoints('in-epoch'));\n return files;\n}\n\nasync function ownedHistory(root: string, path: string): Promise<boolean> {\n const file = await openArtifact(root, path).catch((error: unknown) => {\n // Gone since the listing: nothing left to prune.\n if (error instanceof ArtifactAccessError && error.status === 404) return undefined;\n throw error;\n });\n if (!file) return false;\n try {\n const bytes = await readArtifactBytes(file.handle, Math.min(file.stat.size, HEADER.length));\n return new TextDecoder().decode(bytes) === HEADER;\n } finally {\n await file.handle.close();\n }\n}\n\n/** Mirror history into the session artifact folder. Pruning touches only files carrying this mirror's header. */\nexport async function mirrorCompactionHistory(root: string, entries: readonly CompactionPolicyEntry[]): Promise<void> {\n const files = wantedHistory(entries);\n // ponytail: rewinding to before the first checkpoint keeps the old files; prune on empty if that ever misleads.\n if (files.length === 0) return;\n for (const file of files) await writeArtifactText(root, file.path, file.text);\n const listed = await listArtifacts(root);\n if (listed.error) throw new Error(listed.error);\n const wanted = new Set(files.map((file) => file.path));\n const stale = listed.items.filter((item) => HISTORY_PATH.test(item.path) && !wanted.has(item.path));\n for (const item of stale) if (await ownedHistory(root, item.path)) await removeArtifact(root, item.path);\n for (const folder of new Set(stale.map((item) => item.path.slice(0, item.path.lastIndexOf('/')))))\n await removeArtifact(root, folder);\n}\n","/**\n * Picks the absolute token checkpoints configured for the model a session is running.\n *\n * DESIGN PATTERNS:\n * - Pure decision function, so the matching rule is unit-testable without a session,\n * a config file or a filesystem\n * - First match in file order wins, so a reader resolves a model by reading down the\n * list rather than by working out which pattern is the most specific\n * - A model matching nothing returns no overrides at all, which leaves the ratio\n * ladder exactly as it behaves without this feature\n *\n * AVOID:\n * - Stripping a thinking suffix the way subagent model scope does. That matches\n * free-typed config strings; this matches a resolved `Model`, whose `id` carries\n * the level in a separate field and never in the id itself.\n * - Matching a bare pattern against `provider/id`. The glob wildcard does not cross\n * the separator, so the subject has to follow the pattern's own shape.\n */\n\nimport type { AutocompactOverrideConfig } from '@agimon-ai/po-config';\nimport { minimatch } from 'minimatch';\n\nimport type { AutocompactTokenOverrides } from '../../types/autocompact';\n\n/** The parts of a resolved model the rules match on. */\nexport interface AutocompactModelIdentity {\n id: string;\n provider: string;\n}\n\n/**\n * A pattern naming a provider is matched against `provider/id`, anything else\n * against the bare id. `*` does not cross `/`, so a bare pattern tested against a\n * qualified subject would never match and would read as a silently dead rule.\n */\nfunction matchesModelPattern(pattern: string, model: AutocompactModelIdentity): boolean {\n const subject = pattern.includes('/') ? `${model.provider}/${model.id}` : model.id;\n return minimatch(subject, pattern, { nocase: true });\n}\n\nexport function resolveModelTokenOverrides(\n model: AutocompactModelIdentity | undefined,\n overrides: readonly AutocompactOverrideConfig[],\n): AutocompactTokenOverrides {\n if (!model) return {};\n const matched = overrides.find((entry) => matchesModelPattern(entry.model, model));\n if (!matched) return {};\n const { pass1, pass2, pass3 } = matched.tokens;\n return {\n ...(pass1 === undefined ? {} : { 1: pass1 }),\n ...(pass2 === undefined ? {} : { 2: pass2 }),\n ...(pass3 === undefined ? {} : { 3: pass3 }),\n };\n}\n","import type { ExtensionContext } from '@earendil-works/pi-coding-agent';\n\nconst THINKING_SUFFIX_PATTERN = /:(off|minimal|low|medium|high|xhigh|max)$/;\n\nexport interface SummarizationModel {\n model: NonNullable<ExtensionContext['model']>;\n thinkingLevel?: NonNullable<ExtensionContext['thinkingLevel']>;\n}\n\nexport interface ModelReference {\n provider: string;\n modelId: string;\n thinking?: NonNullable<ExtensionContext['thinkingLevel']>;\n}\n\n/** Splits a `provider/model` reference, tolerating the optional thinking suffix. */\nexport function parseModelReference(reference: string): ModelReference | undefined {\n const trimmed = reference.trim();\n const thinking = THINKING_SUFFIX_PATTERN.exec(trimmed)?.[1] as SummarizationModel['thinkingLevel'];\n const identity = trimmed.replace(THINKING_SUFFIX_PATTERN, '');\n const separator = identity.indexOf('/');\n if (separator <= 0 || separator >= identity.length - 1) return undefined;\n return {\n provider: identity.slice(0, separator),\n modelId: identity.slice(separator + 1),\n ...(thinking ? { thinking } : {}),\n };\n}\n","import { artifactRoot } from '@agimon-ai/po-artifact/artifactFiles';\nimport {\n PO_CONTEXT_CONTRIBUTIONS_SERVICE,\n requirePoContextContributions,\n type PoContextContributionsService,\n} from '@agimon-ai/po-core/contextContributions';\nimport type { PoFooterContributionHandle } from '@agimon-ai/po-core/footer';\nimport type { PoHeadlessExecutionContext, PoHeadlessHook } from '@agimon-ai/po-core/headless';\nimport { PO_UI_HUB_SERVICE, requirePoUiHub } from '@agimon-ai/po-core/uiHub';\n\nimport {\n CHECKPOINT_MESSAGE_TYPE,\n CONTEXT_MESSAGE_TYPE,\n MAX_INVALID_CHECKPOINT_ATTEMPTS,\n RESUME_MESSAGE_TYPE,\n RUNTIME_STATE_MESSAGE_TYPE,\n STATE_CUSTOM_TYPE,\n STATE_VERSION,\n} from '../../constants/autocompact';\nimport {\n FOOTER_ORDER,\n FOOTER_SOURCE,\n PLAN_DOCUMENT_ENTRY,\n SLOW_CONTEXT_HOOK_MS,\n STATUS_KEY,\n} from '../../constants/runtime';\nimport type { AutocompactContextDetails, AutocompactMessage, AutocompactState } from '../../types/autocompact';\nimport {\n autocompactRuntimeConfig,\n checkpointInstructions,\n formatRuntimeState,\n latestPlanSnapshot,\n readContextContributionsSnapshot,\n runtimeStateSnapshot,\n} from '../autocompactRuntime';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from '../autocompactTelemetry';\nimport { isHistoryEntry, mirrorCompactionHistory } from '../compactionHistory';\nimport {\n baselineUsageIsSettled,\n checkpointRequestDetails,\n checkpointSummaryFromEntry,\n contextDetailsFromUnknown,\n createInitialState,\n createRequestId,\n customMessage,\n effectiveThresholds,\n fileDetailsFromUnknown,\n fileOperationsFromMessages,\n isStructuredCheckpoint,\n latestCheckpointArtifactEntry,\n mergeFileDetails,\n parseCheckpointDecision,\n parseState,\n projectContextMessages,\n withCanonicalFileSections,\n type CompactionPolicyEntry,\n} from '../compactionPolicy';\nimport { resolveModelTokenOverrides } from '../modelOverrides';\nimport { parseModelReference } from '../summarizationModel';\nimport type { NativeAutocompactDependencies, NativeAutocompactRuntime } from './type';\n\n/** Exact canonical-prefix comparison refuses to apply summaries to edited or replaced evidence. */\nfunction tailAfter(\n snapshot: readonly AutocompactMessage[],\n current: readonly AutocompactMessage[],\n): AutocompactMessage[] | undefined {\n if (\n snapshot.length > current.length ||\n snapshot.some((message, index) => JSON.stringify(message) !== JSON.stringify(current[index]))\n )\n return undefined;\n return current.slice(snapshot.length);\n}\n\nfunction leaf(entries: readonly CompactionPolicyEntry[]): string {\n return (\n entries.findLast(\n (entry) =>\n entry.type !== 'custom' ||\n (entry.customType !== STATE_CUSTOM_TYPE && entry.customType !== CHECKPOINT_MESSAGE_TYPE),\n )?.id ?? 'root'\n );\n}\n\nexport function createNativeAutocompact(dependencies: NativeAutocompactDependencies = {}): NativeAutocompactRuntime {\n const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();\n let active = true;\n let generation = 0;\n let state: AutocompactState = createInitialState();\n let snapshot: AutocompactMessage[] | undefined;\n let previousSnapshot: AutocompactMessage[] | undefined;\n let context: PoHeadlessExecutionContext | undefined;\n let contributions: PoContextContributionsService | undefined;\n let controller: AbortController | undefined;\n let serial: Promise<void> = Promise.resolve();\n const work = new Set<Promise<void>>();\n const applied = new Set<string>();\n const invalid = new Set<string>();\n let configFailureReported = false;\n let footer: PoFooterContributionHandle | undefined;\n let navigating = false;\n let degraded = false;\n let lastNativeCompactionId: string | undefined;\n let checkpointBoundary:\n | ReturnType<NonNullable<PoHeadlessExecutionContext['session']['registerCheckpointBoundary']>>\n | undefined;\n let mirrorQueued = false;\n let historyWarnedSession: string | undefined;\n\n const attributes = () => ({\n 'pi.session.id': context?.sessionId ?? '',\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': state.pass,\n ...(state.requestId ? { 'autocompact.request.id': state.requestId } : {}),\n ...(state.snapshotLeafId ? { 'autocompact.snapshot_leaf_id': state.snapshotLeafId } : {}),\n ...(state.snapshotTokens === undefined ? {} : { 'autocompact.tokens_before': state.snapshotTokens }),\n });\n const configured = (execution: PoHeadlessExecutionContext) =>\n autocompactRuntimeConfig(\n execution.repoRoot,\n (error) => {\n if (!configFailureReported) {\n configFailureReported = true;\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.configurationLoadFailed, error, {\n ...attributes(),\n 'failure.kind': 'configuration',\n });\n // With admitted settings unreadable autocompact stands down, so the person is told rather than left to guess.\n if (dependencies.modes)\n void Promise.allSettled([\n Promise.resolve().then(() =>\n execution.client.notify({\n body: `Po autocompact is paused until its configuration is available: ${error instanceof Error ? error.message : String(error)}`,\n level: 'warning',\n }),\n ),\n ]);\n }\n },\n dependencies.modes,\n );\n const alive = (version: number) => active && !navigating && generation === version;\n const refreshStatus = (execution: PoHeadlessExecutionContext) => {\n const phase =\n state.phase === 'checkpoint_pending'\n ? 'summarizing'\n : state.phase === 'checkpoint_ready'\n ? 'applying'\n : undefined;\n footer?.update(phase ? { fullText: `Compacting p${state.pass}`, compactText: `C${state.pass}` } : undefined);\n execution.client.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : undefined);\n };\n const enqueue = (callback: () => Promise<void>): Promise<void> => {\n const version = generation;\n const operation = serial.then(async () => {\n if (alive(version)) await callback();\n });\n serial = operation.catch(() => undefined);\n return operation;\n };\n const persist = async (execution: PoHeadlessExecutionContext, version: number) => {\n if (!alive(version)) return;\n await execution.session.appendCustomEntry(STATE_CUSTOM_TYPE, {\n ...state,\n nativeLastCompactionId: lastNativeCompactionId,\n });\n if (alive(version)) refreshStatus(execution);\n };\n const clear = () => {\n delete state.requestId;\n delete state.snapshotLeafId;\n delete state.snapshotTokens;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n snapshot = undefined;\n };\n const fail = async (\n execution: PoHeadlessExecutionContext,\n version: number,\n error: unknown,\n malformed = false,\n kind:\n | 'empty_checkpoint'\n | 'evidence_changed'\n | 'configuration'\n | 'persistence'\n | 'validation'\n | 'unknown' = 'unknown',\n ) => {\n if (!alive(version)) return;\n degraded = true;\n const eventAttributes = attributes();\n const attempts = state.invalidAttempts + 1;\n const pass = state.pass;\n const failedLeaf = state.snapshotLeafId;\n state.invalidAttempts += 1;\n if (state.invalidAttempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS) {\n state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);\n state.exhaustedPasses.push(pass);\n state.invalidAttempts = 0;\n }\n state.phase = 'waiting';\n clear();\n state.lastAttemptLeafId = failedLeaf;\n const errors = [error];\n try {\n await persist(execution, version);\n } catch (persistError) {\n errors.push(persistError);\n }\n if (!alive(version)) return;\n // Reporting is best effort: neither sink may prevent recovery or the native-compaction fallback.\n await Promise.allSettled([\n Promise.resolve().then(() =>\n execution.client.notify({\n body: `Po autocompact summarization pass ${pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n level: 'error',\n }),\n ),\n ...errors.map((failure, index) =>\n Promise.resolve().then(() =>\n telemetry.recordError(\n malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed,\n failure,\n {\n ...eventAttributes,\n 'failure.kind': index === 0 ? kind : 'persistence',\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS,\n },\n // The summarizer's failure is the only clue to why a pass failed; the sink redacts secrets.\n { includeException: true },\n ),\n ),\n ),\n ]);\n };\n // Stream history newest first, keeping only matching entries (oldest first), so large custom journals never pile up.\n const matching = async (\n execution: PoHeadlessExecutionContext,\n keep: (entry: CompactionPolicyEntry) => boolean,\n stopAt?: string,\n ) => {\n const entries: CompactionPolicyEntry[] = [];\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n if (entry.id === stopAt) break;\n if (keep(entry)) entries.push(entry);\n }\n return entries.reverse();\n };\n // Snapshot metadata can precede the context boundary: read only the newest plan and, when asked, checkpoint artifact.\n const policyEntries = async (execution: PoHeadlessExecutionContext, withCheckpoint: boolean) => {\n const entries = [\n ...(await execution.session.entries({\n type: 'custom',\n customType: PLAN_DOCUMENT_ENTRY,\n limit: 1,\n })),\n ] as unknown as CompactionPolicyEntry[];\n if (withCheckpoint) {\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n if (!latestCheckpointArtifactEntry([entry])) continue;\n entries.push(entry);\n break;\n }\n }\n return entries;\n };\n const contextBranch = async (execution: PoHeadlessExecutionContext) => {\n const entries: CompactionPolicyEntry[] = [];\n let foundLeaf = false;\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n const isLeaf = leaf([entry]) !== 'root';\n // Custom journals do not contribute model context. Keep only the newest leaf identity.\n if (entry.type !== 'custom' || (!foundLeaf && isLeaf)) entries.push(entry);\n if (isLeaf) foundLeaf = true;\n if (entry.type === 'compaction' || customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE) break;\n }\n return entries.reverse();\n };\n const canonical = async (execution: PoHeadlessExecutionContext, entries: CompactionPolicyEntry[]) => {\n if (!execution.session.contextMessages) throw new Error('Canonical context is unavailable for autocompact.');\n return projectContextMessages(\n (await execution.session.contextMessages()) as unknown as AutocompactMessage[],\n entries,\n ).messages;\n };\n // History is a convenience copy: its failure is reported once per session and never touches compaction state.\n // Never await this inside a queued job; it queues behind the job that schedules it.\n const scheduleMirror = (execution: PoHeadlessExecutionContext) => {\n if (mirrorQueued) return;\n mirrorQueued = true;\n void enqueue(async () => {\n mirrorQueued = false;\n try {\n await mirrorCompactionHistory(\n artifactRoot(execution.sessionId, execution.environment),\n await matching(execution, isHistoryEntry),\n );\n } catch (error) {\n const warn = historyWarnedSession !== execution.sessionId;\n historyWarnedSession = execution.sessionId;\n await Promise.allSettled([\n Promise.resolve().then(() =>\n telemetry.recordWarning(AUTOCOMPACT_EVENT.historyWriteFailed, error, attributes()),\n ),\n ...(warn\n ? [\n Promise.resolve().then(() =>\n execution.client.notify({\n body: `Po autocompact could not save compaction history: ${error instanceof Error ? error.message : String(error)}`,\n level: 'warning',\n }),\n ),\n ]\n : []),\n ]);\n }\n }).finally(() => {\n mirrorQueued = false;\n });\n };\n const contributionSnapshot = async (execution: PoHeadlessExecutionContext) => {\n const result = readContextContributionsSnapshot(contributions);\n for (const error of result.errors) {\n await execution.client.notify({\n body: `Po autocompact context contribution degraded (${error.source}/${error.id}): ${error.message}`,\n level: 'warning',\n });\n await telemetry.recordWarning(AUTOCOMPACT_EVENT.contextContributionDegraded, new Error(error.message), {\n ...attributes(),\n 'autocompact.context_contribution.source': error.source,\n 'autocompact.context_contribution.id': error.id,\n 'autocompact.context_contribution.order': error.order,\n });\n }\n return result;\n };\n const runtimeState = async (\n execution: PoHeadlessExecutionContext,\n entries: CompactionPolicyEntry[],\n version: number,\n appendMessage: PoHeadlessExecutionContext['session']['appendMessage'] = checkpointBoundary?.appendMessage.bind(\n checkpointBoundary,\n ),\n ) => {\n const saved = runtimeStateSnapshot(entries, await contributionSnapshot(execution));\n if (!alive(version)) return;\n await appendMessage?.({\n type: RUNTIME_STATE_MESSAGE_TYPE,\n text: formatRuntimeState(saved),\n display: false,\n details: { version: 2, ...saved },\n });\n return {\n 'autocompact.runtime.plan_present': Boolean(saved.planPath),\n 'autocompact.runtime.contribution_count': saved.contributions.length,\n 'autocompact.runtime.contribution_error_count': saved.contributionErrors.length,\n };\n };\n const summaryModel = async (execution: PoHeadlessExecutionContext, configuration: ReturnType<typeof configured>) => {\n const ownReference = configuration.agent?.model ? parseModelReference(configuration.agent.model) : undefined;\n const candidate = ownReference ? `${ownReference.provider}/${ownReference.modelId}` : undefined;\n const reference =\n candidate && execution.textCompletion!.available(candidate)\n ? candidate\n : execution.model\n ? `${execution.model.provider}/${execution.model.id}`\n : '';\n const thinking =\n configuration.agent?.thinking ??\n (reference === candidate ? ownReference?.thinking : undefined) ??\n (await execution.session.readModelSettings?.())?.thinkingLevel;\n return { reference, thinking };\n };\n // Manual compaction summarizes stored entries, which still hold everything this extension only projected away.\n // Commit a checkpoint now instead, folding what arrived since this cycle's staged summary the way pass 3 does.\n const manualCompaction = async (event: { instructions?: unknown }, execution: PoHeadlessExecutionContext) => {\n const configuration = configured(execution);\n if (!configuration.enabled || !execution.textCompletion?.summarize) return;\n try {\n const entries = await contextBranch(execution);\n const pinned = await policyEntries(execution, state.pass > 1);\n const messages = await canonical(execution, entries);\n const delta = state.pass > 1 && previousSnapshot ? tailAfter(previousSnapshot, messages) : undefined;\n const previous = state.pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(pinned)) : undefined;\n const { reference, thinking } = await summaryModel(execution, configuration);\n const instructions = checkpointInstructions(3, {\n plan: latestPlanSnapshot(pinned),\n contextContributions: await contributionSnapshot(execution),\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n });\n const { summary } = parseCheckpointDecision(\n await execution.textCompletion.summarize(reference, {\n messages: (delta ?? messages) as unknown as Record<string, unknown>[],\n instructions:\n typeof event.instructions === 'string' && event.instructions.trim()\n ? `${instructions}\\n\\n${event.instructions}`\n : instructions,\n ...(previous ? { previousSummary: previous } : {}),\n ...(thinking ? { thinkingLevel: thinking } : {}),\n ...(execution.signal ? { signal: execution.signal } : {}),\n }),\n );\n if (!isStructuredCheckpoint(summary)) throw new Error('Summarization returned an incomplete checkpoint.');\n const files = mergeFileDetails(state, fileOperationsFromMessages(messages));\n const usage = await execution.session.contextUsage?.();\n return {\n compaction: {\n summary: withCanonicalFileSections(summary, files),\n tokensBefore: usage?.tokens ?? 0,\n retainedTail: [],\n details: files,\n },\n };\n } catch (error) {\n // The host falls back to native compaction, whose own failure would hide this reason.\n await execution.client.notify({\n body: `Po autocompact manual compaction failed: ${error instanceof Error ? error.message : String(error)}`,\n level: 'error',\n });\n throw error;\n }\n };\n const resetCycle = () => {\n state.phase = 'waiting';\n state.checkpointQueue = [];\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n state.baselinePending = true;\n state.cycle += 1;\n state.pass = 1;\n delete state.lastAttemptLeafId;\n delete state.latestCheckpointSnapshotLeafId;\n clear();\n previousSnapshot = undefined;\n };\n const applyReady = async (\n execution: PoHeadlessExecutionContext,\n version: number,\n appendMessage: NonNullable<typeof checkpointBoundary>['appendMessage'],\n ): Promise<boolean> => {\n if (state.phase !== 'checkpoint_ready' || !state.pendingCheckpoint || !state.requestId || !state.snapshotLeafId)\n return false;\n const decision = parseCheckpointDecision(state.pendingCheckpoint);\n if (!isStructuredCheckpoint(decision.summary)) {\n await fail(execution, version, new Error('Summarization returned an incomplete checkpoint.'), true, 'validation');\n return false;\n }\n const entries = await contextBranch(execution);\n const messages = await canonical(execution, entries);\n if (!alive(version)) return false;\n // Persisted legacy pending summaries lack canonical evidence. Retry rather than fabricate a retained tail.\n const tail = snapshot && tailAfter(snapshot, messages);\n if (!tail) {\n await fail(\n execution,\n version,\n new Error('Canonical checkpoint evidence changed; summary must be regenerated.'),\n false,\n 'evidence_changed',\n );\n return false;\n }\n const pass = state.pass;\n if (pass === 1 || (pass === 2 && decision.shouldCompact !== true)) {\n await execution.session.appendCustomEntry(CHECKPOINT_MESSAGE_TYPE, {\n ...checkpointRequestDetails(state.cycle, pass, state.requestId),\n summary: decision.summary,\n });\n if (!alive(version)) return false;\n previousSnapshot = snapshot;\n state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;\n state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);\n state.pass = pass === 1 ? 2 : 3;\n state.phase = 'waiting';\n state.invalidAttempts = 0;\n clear();\n await persist(execution, version);\n scheduleMirror(execution);\n return false;\n }\n const files = mergeFileDetails(state, fileOperationsFromMessages(messages));\n const details: AutocompactContextDetails = {\n ...files,\n poAutocompact: {\n version: STATE_VERSION,\n cycle: state.cycle,\n pass,\n requestId: state.requestId,\n snapshotLeafId: state.snapshotLeafId,\n tokensBefore: state.snapshotTokens ?? 0,\n },\n retainedMessages: tail,\n };\n const idle = (await execution.session.activity()).isIdle;\n if (!alive(version)) return false;\n // The marker heads native context, so native compaction and context reads skip everything before it.\n const id = await appendMessage(\n {\n type: CONTEXT_MESSAGE_TYPE,\n text: withCanonicalFileSections(decision.summary, files),\n display: false,\n details,\n },\n { resetContext: { retainedMessages: tail as unknown as Record<string, unknown>[] } },\n );\n if (!alive(version) || !id) return false;\n await execution.session.setLabel?.(id, `autocompact:c${state.cycle}:p${pass}`);\n if (!alive(version)) return false;\n const runtimeAttributes = await runtimeState(\n execution,\n await policyEntries(execution, false),\n version,\n appendMessage,\n );\n if (!alive(version)) return false;\n const committedAttributes = attributes();\n state.readFiles = files.readFiles;\n state.modifiedFiles = files.modifiedFiles;\n resetCycle();\n await persist(execution, version);\n scheduleMirror(execution);\n if (!alive(version)) return false;\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextCommitted, {\n ...committedAttributes,\n 'autocompact.message_count.before': messages.length,\n 'autocompact.message_count.retained': tail.length,\n 'autocompact.apply_mode': idle ? 'idle' : 'turn_end',\n ...runtimeAttributes,\n });\n if (idle && alive(version))\n await execution.session.admitPrompt?.(\n \"Asynchronous compaction completed. Continue from the compacted checkpoint's immediate next action without repeating completed work.\",\n 'steer',\n undefined,\n `${RESUME_MESSAGE_TYPE}:${details.poAutocompact.requestId}`,\n );\n return true;\n };\n const ensureCheckpointBoundary = (execution: PoHeadlessExecutionContext) => {\n if (checkpointBoundary) return;\n if (!execution.session.registerCheckpointBoundary) throw new Error('Native checkpoint boundaries are unavailable.');\n checkpointBoundary = execution.session.registerCheckpointBoundary(async (boundary) => {\n if (!active || navigating || boundary.signal?.aborted) return;\n const current = context ?? execution;\n await enqueue(() =>\n boundary.signal?.aborted ? Promise.resolve() : progress(current, true, boundary.appendMessage.bind(boundary)),\n );\n });\n };\n const advance = async (\n execution: PoHeadlessExecutionContext,\n allowBusy = false,\n appendMessage = checkpointBoundary?.appendMessage.bind(checkpointBoundary),\n ) => {\n const version = generation;\n context = execution;\n const activity = await execution.session.activity();\n if (!alive(version) || activity.hasPendingMessages) return;\n if (appendMessage && (activity.isIdle || allowBusy)) {\n if (await applyReady(execution, version, appendMessage)) return;\n }\n if (!alive(version) || state.phase !== 'waiting') return;\n const configuration = configured(execution);\n if (!configuration.enabled || !execution.session.contextUsage || !execution.textCompletion?.summarize) return;\n const usage = await execution.session.contextUsage();\n if (\n !alive(version) ||\n !usage ||\n typeof usage.tokens !== 'number' ||\n !Number.isFinite(usage.tokens) ||\n usage.tokens < 0\n )\n return;\n const tokens = usage.tokens;\n const thresholds = effectiveThresholds(\n usage.contextWindow,\n state.baselineTokens,\n configuration.ratios,\n resolveModelTokenOverrides(execution.model, configuration.overrides),\n );\n if (\n !state.baselinePending &&\n !state.checkpointQueue.length &&\n !([1, 2, 3] as const).some(\n (pass) => pass >= state.pass && !state.exhaustedPasses.includes(pass) && tokens >= thresholds[pass],\n )\n )\n return;\n const entries = await contextBranch(execution);\n if (!alive(version)) return;\n if (state.baselinePending) {\n if (!baselineUsageIsSettled(entries)) return;\n state.baselineTokens = usage.tokens;\n state.baselinePending = false;\n await persist(execution, version);\n return;\n }\n const currentLeaf = leaf(entries);\n if (currentLeaf === state.lastAttemptLeafId) return;\n for (const pass of [1, 2, 3] as const) {\n if (\n pass >= state.pass &&\n !state.checkpointQueue.includes(pass) &&\n !state.exhaustedPasses.includes(pass) &&\n usage.tokens >= thresholds[pass]\n )\n state.checkpointQueue.push(pass);\n }\n const pass = state.checkpointQueue[0];\n if (!pass) return;\n state.pass = pass;\n const checkpointEntries = await policyEntries(execution, pass > 1);\n const messages = await canonical(execution, entries);\n const steering = await contributionSnapshot(execution);\n if (!alive(version)) return;\n snapshot = messages;\n const previous =\n pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(checkpointEntries)) : undefined;\n const requestId = createRequestId(execution.sessionId, state.cycle, pass, currentLeaf);\n state.phase = 'checkpoint_pending';\n state.requestId = requestId;\n state.snapshotLeafId = currentLeaf;\n state.snapshotTokens = usage.tokens;\n delete state.lastAttemptLeafId;\n delete state.pendingCheckpoint;\n await persist(execution, version);\n if (!alive(version)) return;\n degraded = false;\n controller?.abort();\n controller = new AbortController();\n const signal = controller.signal;\n const requestAttributes = { ...attributes(), 'autocompact.message_count.before': messages.length };\n const delta = previousSnapshot ? tailAfter(previousSnapshot, messages) : undefined;\n let failureKind: 'configuration' | 'unknown' | 'persistence' = 'configuration';\n const completion = telemetry\n .runInSpan('po_autocompact.checkpoint', requestAttributes, async () => {\n const { reference, thinking } = await summaryModel(execution, configuration);\n failureKind = 'unknown';\n if (!alive(version) || signal.aborted) return '';\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, requestAttributes);\n return execution.textCompletion!.summarize!(reference, {\n messages: (pass > 1 && delta ? delta : messages) as unknown as Record<string, unknown>[],\n instructions: checkpointInstructions(pass, {\n plan: latestPlanSnapshot(checkpointEntries),\n contextContributions: steering,\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n }),\n ...(previous ? { previousSummary: previous } : {}),\n ...(thinking ? { thinkingLevel: thinking } : {}),\n signal,\n });\n })\n .then(async (summary) => {\n await enqueue(async () => {\n if (!alive(version) || signal.aborted || state.requestId !== requestId) return;\n if (!summary.trim()) {\n await fail(\n execution,\n version,\n new Error('Summarization returned an empty checkpoint.'),\n false,\n 'empty_checkpoint',\n );\n return;\n }\n state.phase = 'checkpoint_ready';\n state.pendingCheckpoint = summary.trim();\n failureKind = 'persistence';\n await persist(execution, version);\n failureKind = 'unknown';\n if (!alive(version)) return;\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {\n ...requestAttributes,\n 'autocompact.checkpoint.characters': summary.length,\n });\n if ((await execution.session.activity()).isIdle && alive(version)) await progress(execution);\n });\n })\n .catch(async (error: unknown) => {\n await enqueue(async () => {\n if (alive(version) && state.requestId === requestId)\n await fail(execution, version, error, false, failureKind);\n });\n });\n work.add(completion);\n void completion.then(\n () => work.delete(completion),\n () => work.delete(completion),\n );\n };\n const progress = async (\n execution: PoHeadlessExecutionContext,\n allowBusy = false,\n appendMessage?: Parameters<typeof advance>[2],\n ) => {\n const version = generation;\n try {\n ensureCheckpointBoundary(execution);\n await advance(execution, allowBusy, appendMessage);\n } catch (error) {\n try {\n await fail(execution, version, error, false, 'persistence');\n } finally {\n // Infrastructure failures can recover without a new conversation leaf.\n if (alive(version)) delete state.lastAttemptLeafId;\n }\n }\n };\n const load = async (execution: PoHeadlessExecutionContext) => {\n if (!active) return;\n navigating = false;\n generation += 1;\n const version = generation;\n controller?.abort(new Error('Autocompact session generation changed.'));\n controller = undefined;\n context = execution;\n applied.clear();\n invalid.clear();\n const saved = await execution.session.customSnapshot?.(STATE_CUSTOM_TYPE);\n if (!alive(version)) return;\n const entry = (saved?.available ? saved.entry : undefined) as unknown as CompactionPolicyEntry | undefined;\n const data =\n entry?.type === 'custom' && entry.data && typeof entry.data === 'object'\n ? (entry.data as Record<string, unknown>)\n : undefined;\n state = parseState(data) ?? createInitialState();\n lastNativeCompactionId = typeof data?.nativeLastCompactionId === 'string' ? data.nativeLastCompactionId : undefined;\n const validMessages = (value: unknown): value is AutocompactMessage[] =>\n Array.isArray(value) &&\n value.every((message) => message && typeof message === 'object' && typeof message.role === 'string');\n snapshot = validMessages(data?.nativeSnapshot) ? data.nativeSnapshot : undefined;\n previousSnapshot = validMessages(data?.nativePreviousSnapshot) ? data.nativePreviousSnapshot : undefined;\n // A marker can commit before its following state entry. Recover only the exact\n // request after the saved state, rather than retrying against already-compacted evidence.\n if (entry?.id && state.phase === 'checkpoint_ready' && state.requestId) {\n const artifacts = await matching(\n execution,\n (item) =>\n (item.type === 'custom' && item.customType === CHECKPOINT_MESSAGE_TYPE) ||\n customMessage(item)?.customType === CONTEXT_MESSAGE_TYPE,\n entry?.id,\n );\n const committed = artifacts.findLast((item) => {\n const message = item.type === 'message' ? item.message : undefined;\n if (message?.role !== 'custom' || message.customType !== CONTEXT_MESSAGE_TYPE) return false;\n const details = contextDetailsFromUnknown(message.details);\n return (\n details !== undefined &&\n details.poAutocompact.requestId === state.requestId &&\n details.poAutocompact.cycle === state.cycle &&\n details.poAutocompact.pass === state.pass &&\n details.poAutocompact.snapshotLeafId === state.snapshotLeafId &&\n isStructuredCheckpoint(checkpointSummaryFromEntry(item) ?? '')\n );\n });\n if (committed?.type === 'message' && committed.message.role === 'custom') {\n const details = contextDetailsFromUnknown(committed.message.details)!;\n state.readFiles = details.readFiles;\n state.modifiedFiles = details.modifiedFiles;\n resetCycle();\n await persist(execution, version);\n } else {\n const staged = artifacts.findLast((item) => {\n if (item.type !== 'custom' || item.customType !== CHECKPOINT_MESSAGE_TYPE) return false;\n const details = item.data as Record<string, unknown> | undefined;\n return (\n details?.version === STATE_VERSION &&\n details.requestId === state.requestId &&\n details.cycle === state.cycle &&\n details.pass === state.pass &&\n isStructuredCheckpoint(checkpointSummaryFromEntry(item) ?? '')\n );\n });\n if (staged && (state.pass === 1 || state.pass === 2)) {\n previousSnapshot = snapshot;\n state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;\n state.checkpointQueue = state.checkpointQueue.filter((pass) => pass !== state.pass);\n state.pass = state.pass === 1 ? 2 : 3;\n state.phase = 'waiting';\n state.invalidAttempts = 0;\n clear();\n await persist(execution, version);\n }\n }\n }\n if (state.phase !== 'waiting' && (state.phase !== 'checkpoint_ready' || !snapshot)) {\n // ponytail: snapshot-free pending work regenerates after restart; durable prefix reconstruction can avoid this cost later.\n state.phase = 'waiting';\n clear();\n delete state.lastAttemptLeafId;\n await persist(execution, version);\n }\n if (!alive(version)) return;\n const progressed = enqueue(() => progress(execution));\n scheduleMirror(execution);\n await progressed;\n };\n const restore = async (execution: PoHeadlessExecutionContext) => {\n const version = generation + 1;\n try {\n await load(execution);\n } catch (error) {\n await fail(execution, version, error);\n }\n };\n const hooks: PoHeadlessHook[] = [\n { event: 'session_start', handle: (_event, execution) => restore(execution) },\n {\n event: 'session_tree',\n handle: (event, execution) => {\n if (!active) return;\n if (event.status === 'started') {\n navigating = true;\n generation += 1;\n controller?.abort(new Error('Autocompact navigation started.'));\n return;\n }\n return restore(execution);\n },\n },\n {\n event: 'turn_end',\n handle: (_event, execution) => enqueue(() => progress(execution)),\n },\n { event: 'agent_settled', handle: (_event, execution) => enqueue(() => progress(execution)) },\n {\n event: 'session_before_compact',\n handle: (event, execution) => {\n if (!active || navigating) return;\n if (event.reason === 'manual') return manualCompaction(event, execution);\n return !degraded &&\n configured(execution).enabled &&\n event.reason === 'threshold' &&\n (state.phase === 'checkpoint_pending' || state.phase === 'checkpoint_ready')\n ? { cancel: true }\n : undefined;\n },\n },\n {\n event: 'context',\n async handle(event, execution) {\n if (!active || navigating || !Array.isArray(event.messages)) return;\n const started = Date.now();\n try {\n const version = generation;\n const entries = await contextBranch(execution);\n if (!alive(version)) return;\n const projection = projectContextMessages(event.messages as AutocompactMessage[], entries);\n if (projection.invalidMarker) {\n const id = leaf(entries);\n if (!invalid.has(id)) {\n invalid.add(id);\n await telemetry.recordError(\n AUTOCOMPACT_EVENT.contextMarkerInvalid,\n new Error('Po autocompact context marker is malformed.'),\n { ...attributes(), 'autocompact.leaf_id': id },\n );\n }\n return;\n }\n if (!projection.marker) return;\n if (!applied.has(projection.marker.requestId)) {\n applied.add(projection.marker.requestId);\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextApplied, {\n ...attributes(),\n 'autocompact.request.id': projection.marker.requestId,\n 'autocompact.cycle': projection.marker.cycle,\n 'autocompact.pass': projection.marker.pass,\n 'autocompact.snapshot_leaf_id': projection.marker.snapshotLeafId,\n 'autocompact.tokens_before': projection.marker.tokensBefore,\n 'autocompact.message_count.before': event.messages.length,\n 'autocompact.message_count.after': projection.messages.length,\n 'autocompact.message_count.retained': projection.retainedMessageCount,\n });\n }\n return alive(version) ? { messages: projection.messages } : undefined;\n } finally {\n const hookMs = Date.now() - started;\n if (active && hookMs >= SLOW_CONTEXT_HOOK_MS)\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextHookSlow, {\n ...attributes(),\n hook_ms: hookMs,\n 'autocompact.message_count': event.messages.length,\n });\n }\n },\n },\n {\n event: 'session_compact',\n handle: (event, execution) => {\n if (\n !active ||\n event.status !== 'completed' ||\n typeof event.entryId !== 'string' ||\n event.entryId === lastNativeCompactionId\n )\n return;\n const observedGeneration = generation;\n return enqueue(async () => {\n const entries = (await execution.session.entries({\n type: 'compaction',\n limit: 1,\n })) as unknown as CompactionPolicyEntry[];\n const compacted = entries[0];\n if (\n !alive(observedGeneration) ||\n !compacted ||\n compacted.type !== 'compaction' ||\n compacted.id !== event.entryId ||\n compacted.id === lastNativeCompactionId\n )\n return;\n generation += 1;\n const version = generation;\n controller?.abort(new Error('Native compaction superseded checkpoint.'));\n controller = undefined;\n lastNativeCompactionId = compacted.id;\n const files = mergeFileDetails(\n state,\n undefined,\n fileDetailsFromUnknown('details' in compacted ? compacted.details : undefined),\n );\n state.readFiles = files.readFiles;\n state.modifiedFiles = files.modifiedFiles;\n await execution.session.setLabel?.(compacted.id, `autocompact:c${state.cycle}:external`);\n if (!alive(version)) return;\n const plan = (await execution.session.entries({\n type: 'custom',\n customType: PLAN_DOCUMENT_ENTRY,\n limit: 1,\n })) as unknown as CompactionPolicyEntry[];\n const runtimeAttributes = await runtimeState(execution, plan, version);\n if (!alive(version)) return;\n const nativeAttributes = attributes();\n resetCycle();\n await persist(execution, version);\n scheduleMirror(execution);\n if (alive(version))\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.nativeCompactionCompleted, {\n ...nativeAttributes,\n 'autocompact.native.reason': typeof event.reason === 'string' ? event.reason : 'unknown',\n 'autocompact.native.from_extension': 'fromHook' in compacted && compacted.fromHook === true,\n 'autocompact.tokens_before': compacted.tokensBefore,\n ...runtimeAttributes,\n });\n });\n },\n },\n ];\n return {\n hooks,\n plugin(cordis) {\n cordis.inject([PO_UI_HUB_SERVICE], (injected) => {\n const contribution = requirePoUiHub(injected).registerFooter({\n source: FOOTER_SOURCE,\n id: 'autocompact',\n order: FOOTER_ORDER,\n });\n footer = contribution;\n if (context && active) refreshStatus(context);\n return () => {\n contribution.dispose();\n if (footer === contribution) footer = undefined;\n };\n });\n cordis.inject([PO_CONTEXT_CONTRIBUTIONS_SERVICE], (injected) => {\n const service = requirePoContextContributions(injected);\n contributions = service;\n return () => {\n if (contributions === service) contributions = undefined;\n };\n });\n },\n start: restore,\n async stop() {\n active = false;\n checkpointBoundary?.dispose();\n checkpointBoundary = undefined;\n generation += 1;\n controller?.abort(new Error('Autocompact is shutting down.'));\n await Promise.allSettled([...work, serial]);\n context?.client.setStatus(STATUS_KEY, undefined);\n footer?.update(undefined);\n footer = undefined;\n context = undefined;\n contributions = undefined;\n await telemetry.shutdown();\n },\n };\n}\n","import { defineRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { admittedModes } from '../../../../services/admittedModes';\nimport { createAutocompactTelemetry } from '../../../../services/autocompactTelemetry';\nimport { createNativeAutocompact } from '../../../../services/nativeAutocompact';\n\nexport default defineRoot(({ agent, context }: PoServerPluginContext) => {\n const runtime = createNativeAutocompact({\n telemetry: createAutocompactTelemetry({ env: agent?.context.environment, cwd: agent?.context.cwd }),\n modes: admittedModes(context),\n });\n return { value: runtime, services: [runtime.plugin], onDispose: runtime.stop };\n});\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'agent_settled')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'context')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_before_compact')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_compact')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_start')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_tree')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'turn_end')!,\n);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport hookAgentSettled from '../src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server';\nimport hookContext from '../src/extensions/workspaces/sessions/(backend)/hook/context.server';\nimport hookSessionBeforeCompact from '../src/extensions/workspaces/sessions/(backend)/hook/session-before-compact.server';\nimport hookSessionCompact from '../src/extensions/workspaces/sessions/(backend)/hook/session-compact.server';\nimport hookSessionStart from '../src/extensions/workspaces/sessions/(backend)/hook/session-start.server';\nimport hookSessionTree from '../src/extensions/workspaces/sessions/(backend)/hook/session-tree.server';\nimport hookTurnEnd from '../src/extensions/workspaces/sessions/(backend)/hook/turn-end.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-autocompact',\n providerOverrides: composeServerProviderOverrides(rootSession),\n injects: composeRootInjects({ session: [rootSession] }),\n session: async (context) => {\n const scopeSession = await context.scopeRoot('session', rootSession, context);\n const contextSession = { ...context, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeSession),\n get hooks(): PoServerSessionPlugin['hooks'] { return [via({ event: 'agent_settled' }, at(hookAgentSettled, contextSession)), via({ event: 'context' }, at(hookContext, contextSession)), via({ event: 'session_before_compact' }, at(hookSessionBeforeCompact, contextSession)), via({ event: 'session_compact' }, at(hookSessionCompact, contextSession)), via({ event: 'session_start' }, at(hookSessionStart, contextSession)), via({ event: 'session_tree' }, at(hookSessionTree, contextSession)), via({ event: 'turn_end' }, at(hookTurnEnd, contextSession))]; },\n services: [...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;;;;;;;;ACOA,MAAM,eAAe;AACrB,MAAM,eAAe;AAErB,MAAa,oBAAoB;CAC/B,mBAAmB;CACnB,qBAAqB;CACrB,kBAAkB;CAClB,mBAAmB;CACnB,yBAAyB;CACzB,6BAA6B;CAC7B,kBAAkB;CAClB,gBAAgB;CAChB,sBAAsB;CACtB,iBAAiB;CACjB,2BAA2B;CAC3B,oBAAoB;AACtB;AA2BA,SAAgB,2BAA2B,UAAuC,CAAC,GAAyB;CAC1G,MAAM,aAAA,GAAyBA,6BAAAA,kBAAAA,CAAkB;EAC/C,aAAa;EACb,aAAa;EACb,KAAK,QAAQ;EACb,eAAe,QAAQ;EACvB,KAAK,QAAQ;EACb,kBAAkB,QAAQ;EAC1B,MAAM,QAAQ;EACd,YAAY;EACZ,cAAc;CAChB,CAAC;CACD,OAAO;EACL,cAAc,OAAO,OAAO,YAAY,iBACtC,UAAU,YAAY,OAAO,OAAO,YAAY,YAAY;EAC9D,gBAAgB,OAAO,OAAO,eAAe,UAAU,cAAc,OAAO,OAAO,UAAU;EAC7F,cAAc,OAAO,eAAe,UAAU,YAAY,OAAO,UAAU;EAC3E,YAAY,MAAM,YAAY,aAAa,UAAU,UAAU,MAAM,YAAY,QAAQ;EACzF,aAAa,UAAU,MAAM;EAC7B,gBAAgB,UAAU,SAAS;CACrC;AACF;;;ACtEA,MAAa,sBAAsB;AACnC,MAAa,gBAAgB;AAE7B,MAAa,aAAa;;;AC4B1B,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,SAAgB,mBAAmB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-ai/po-core/uiHub";
8
8
  import { loadPoConfig } from "@agimon-ai/po-config";
9
9
  import { minimatch } from "minimatch";
10
+ //#endregion
10
11
  //#region src/services/autocompactTelemetry/index.ts
11
12
  const SERVICE_NAME = "po-autocompact";
12
13
  const PACKAGE_NAME = "@agimon-ai/po-autocompact";
@@ -158,18 +159,31 @@ const DEFAULT_RUNTIME_CONFIG = {
158
159
  ratios: {},
159
160
  overrides: []
160
161
  };
162
+ /** While admitted settings cannot be read a disable could be hidden, so autocompact stands down for the host. */
163
+ const UNAVAILABLE_RUNTIME_CONFIG = {
164
+ enabled: false,
165
+ ratios: {},
166
+ overrides: []
167
+ };
161
168
  /**
162
169
  * What the Po config says about this package.
163
170
  *
164
171
  * `modes.autocompact` is read first and `modes.planning.subagents` is the
165
172
  * fallback, because summarization borrowed the planning subagent model before
166
173
  * it had keys of its own and existing files still spell it that way.
174
+ *
175
+ * A host that admits its configuration passes `admitted`, and that is read instead of the files. Reading it
176
+ * failing is reported and stands autocompact down, where unreadable files keep the session model and stay on.
167
177
  */
168
- function autocompactRuntimeConfig(root, onLoadFailure) {
178
+ function autocompactRuntimeConfig(root, onLoadFailure, admitted) {
169
179
  let modes;
170
180
  try {
171
- modes = loadPoConfig(root).modes;
181
+ modes = admitted ? admitted() : loadPoConfig(root).modes;
172
182
  } catch (error) {
183
+ if (admitted) {
184
+ onLoadFailure?.(error);
185
+ return UNAVAILABLE_RUNTIME_CONFIG;
186
+ }
173
187
  process.emitWarning("Po autocompact configuration could not be loaded; using the active session model instead.");
174
188
  onLoadFailure?.(error);
175
189
  return DEFAULT_RUNTIME_CONFIG;
@@ -394,8 +408,12 @@ function createNativeAutocompact(dependencies = {}) {
394
408
  ...attributes(),
395
409
  "failure.kind": "configuration"
396
410
  });
411
+ if (dependencies.modes) Promise.allSettled([Promise.resolve().then(() => execution.client.notify({
412
+ body: `Po autocompact is paused until its configuration is available: ${error instanceof Error ? error.message : String(error)}`,
413
+ level: "warning"
414
+ }))]);
397
415
  }
398
- });
416
+ }, dependencies.modes);
399
417
  const alive = (version) => active && !navigating && generation === version;
400
418
  const refreshStatus = (execution) => {
401
419
  const phase = state.phase === "checkpoint_pending" ? "summarizing" : state.phase === "checkpoint_ready" ? "applying" : void 0;
@@ -1055,11 +1073,14 @@ function createNativeAutocompact(dependencies = {}) {
1055
1073
  }
1056
1074
  //#endregion
1057
1075
  //#region src/extensions/workspaces/sessions/(backend)/root.server.ts
1058
- var root_server_default = defineRoot(({ agent }) => {
1059
- const runtime = createNativeAutocompact({ telemetry: createAutocompactTelemetry({
1060
- env: agent?.context.environment,
1061
- cwd: agent?.context.cwd
1062
- }) });
1076
+ var root_server_default = defineRoot(({ agent, context }) => {
1077
+ const runtime = createNativeAutocompact({
1078
+ telemetry: createAutocompactTelemetry({
1079
+ env: agent?.context.environment,
1080
+ cwd: agent?.context.cwd
1081
+ }),
1082
+ modes: void 0
1083
+ });
1063
1084
  return {
1064
1085
  value: runtime,
1065
1086
  services: [runtime.plugin],
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":["rootSession","hookAgentSettled","hookContext","hookSessionBeforeCompact","hookSessionCompact","hookSessionStart","hookSessionTree","hookTurnEnd"],"sources":["../../src/services/autocompactTelemetry/index.ts","../../src/constants/runtime.ts","../../src/services/autocompactRuntime/index.ts","../../src/services/compactionHistory/index.ts","../../src/services/modelOverrides/index.ts","../../src/services/summarizationModel/index.ts","../../src/services/nativeAutocompact/index.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/context.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-before-compact.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-compact.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-start.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-tree.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/turn-end.server.ts","../../generated/server.ts"],"sourcesContent":["import {\n createPoTelemetry,\n type PoTelemetry,\n type PoTelemetryErrorOptions,\n type PoTelemetryOptions,\n} from '@agimon-ai/po-core/telemetry';\n\nconst SERVICE_NAME = 'po-autocompact';\nconst PACKAGE_NAME = '@agimon-ai/po-autocompact';\n\nexport const AUTOCOMPACT_EVENT = {\n checkpointStarted: 'po_autocompact.checkpoint_started',\n checkpointCompleted: 'po_autocompact.checkpoint_completed',\n checkpointFailed: 'po_autocompact.checkpoint_failed',\n checkpointInvalid: 'po_autocompact.checkpoint_invalid',\n configurationLoadFailed: 'po_autocompact.configuration_load_failed',\n contextContributionDegraded: 'po_autocompact.context_contribution_degraded',\n contextCommitted: 'po_autocompact.context_committed',\n contextApplied: 'po_autocompact.context_applied',\n contextMarkerInvalid: 'po_autocompact.context_marker_invalid',\n contextHookSlow: 'po_autocompact.context_hook_slow',\n nativeCompactionCompleted: 'po_autocompact.native_compaction_completed',\n historyWriteFailed: 'po_autocompact.history_write_failed',\n} as const;\n\nexport type AutocompactEventName = (typeof AUTOCOMPACT_EVENT)[keyof typeof AUTOCOMPACT_EVENT];\nexport type AutocompactEventAttributes = Record<string, string | number | boolean>;\n\nexport interface AutocompactTelemetryOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<PoTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n}\n\nexport interface AutocompactTelemetry {\n recordError(\n event: AutocompactEventName,\n error: unknown,\n attributes?: AutocompactEventAttributes,\n options?: PoTelemetryErrorOptions,\n ): Promise<void>;\n recordWarning(event: AutocompactEventName, error: unknown, attributes?: AutocompactEventAttributes): Promise<void>;\n recordEvent(event: AutocompactEventName, attributes?: AutocompactEventAttributes): Promise<void>;\n runInSpan<T>(name: string, attributes: AutocompactEventAttributes, callback: () => Promise<T>): Promise<T>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createAutocompactTelemetry(options: AutocompactTelemetryOptions = {}): AutocompactTelemetry {\n const telemetry: PoTelemetry = createPoTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n });\n return {\n recordError: (event, error, attributes, errorOptions) =>\n telemetry.recordError(event, error, attributes, errorOptions),\n recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),\n recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),\n runInSpan: (name, attributes, callback) => telemetry.runInSpan(name, attributes, callback),\n flush: () => telemetry.flush(),\n shutdown: () => telemetry.shutdown(),\n };\n}\n","export const ROOT_WORKING_LEAF = '@root';\nexport const PLAN_DOCUMENT_ENTRY = 'agent-harness-plan-document';\nexport const FOOTER_SOURCE = 'po-autocompact';\nexport const FOOTER_ORDER = 20;\nexport const STATUS_KEY = 'po-autocompact';\nexport const STATE_PHASE = {\n waiting: 'waiting',\n checkpointPending: 'checkpoint_pending',\n checkpointReady: 'checkpoint_ready',\n compacting: 'compacting',\n} as const;\n\n/**\n * Above this, the context hook is worth a telemetry event. Below it the hook is\n * noise against a round trip measured in seconds, and it runs on every request.\n */\nexport const SLOW_CONTEXT_HOOK_MS = 25;\n","import { loadPoConfig, type AutocompactOverrideConfig, type PlanningAgentConfig } from '@agimon-ai/po-config';\nimport {\n PO_CONTEXT_CONTRIBUTIONS_SERVICE,\n type PoContextContributionEntry,\n type PoContextContributionError,\n type PoContextContributionsService,\n type PoContextContributionsSnapshot,\n} from '@agimon-ai/po-core/contextContributions';\n\nimport { PLAN_DOCUMENT_ENTRY } from '../../constants/runtime';\nimport type { AutocompactPass, AutocompactRatioOverrides } from '../../types/autocompact';\nimport type { CompactionPolicyEntry } from '../compactionPolicy';\n\ninterface PlanSnapshot {\n content: string;\n path: string;\n}\n\ninterface SteeringSnapshot {\n plan?: PlanSnapshot;\n contextContributions: PoContextContributionsSnapshot;\n readFiles: string[];\n modifiedFiles: string[];\n}\n\ninterface RuntimeStateSnapshot {\n planPath?: string;\n contributions: readonly PoContextContributionEntry[];\n contributionErrors: readonly PoContextContributionError[];\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function latestPlanSnapshot(branch: readonly CompactionPolicyEntry[]): PlanSnapshot | undefined {\n for (const entry of branch.toReversed()) {\n if (entry.type !== 'custom' || entry.customType !== PLAN_DOCUMENT_ENTRY) continue;\n if (!entry.data || typeof entry.data !== 'object') return undefined;\n const data = entry.data as Record<string, unknown>;\n if (typeof data.content !== 'string' || typeof data.path !== 'string') return undefined;\n return { content: data.content, path: data.path };\n }\n return undefined;\n}\n\nconst EMPTY_CONTEXT_CONTRIBUTIONS: PoContextContributionsSnapshot = Object.freeze({\n entries: Object.freeze([]),\n errors: Object.freeze([]),\n});\n\nexport function readContextContributionsSnapshot(\n service: PoContextContributionsService | undefined,\n): PoContextContributionsSnapshot {\n if (!service) return EMPTY_CONTEXT_CONTRIBUTIONS;\n try {\n return service.snapshot();\n } catch (error) {\n return {\n entries: [],\n errors: [\n {\n source: PO_CONTEXT_CONTRIBUTIONS_SERVICE,\n id: 'service-snapshot',\n label: 'Context contributions',\n order: 0,\n message: errorMessage(error),\n },\n ],\n };\n }\n}\n\nfunction formatContextContributions(snapshot: PoContextContributionsSnapshot): string {\n const sections = snapshot.entries.map((entry) => `### ${entry.label}\\n${entry.text}`);\n sections.push(...snapshot.errors.map((error) => `### ${error.label}\\n(unavailable: ${error.message})`));\n return sections.length > 0 ? sections.join('\\n\\n') : '(no registered context contributions)';\n}\n\nexport function runtimeStateSnapshot(\n branch: readonly CompactionPolicyEntry[],\n contextContributions: PoContextContributionsSnapshot,\n): RuntimeStateSnapshot {\n const plan = latestPlanSnapshot(branch);\n return {\n ...(plan ? { planPath: plan.path } : {}),\n contributions: contextContributions.entries,\n contributionErrors: contextContributions.errors,\n };\n}\n\nexport function formatRuntimeState(snapshot: RuntimeStateSnapshot): string {\n const plan = snapshot.planPath\n ? `Source: ${snapshot.planPath}\\nExact plan content is restored separately by Po Plan.`\n : '(no active plan document)';\n return `<compaction-runtime-state>\nAuthoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.\n<active-plan>\n${plan}\n</active-plan>\n<context-contributions>\n${formatContextContributions({ entries: snapshot.contributions, errors: snapshot.contributionErrors })}\n</context-contributions>\n</compaction-runtime-state>`;\n}\n\nfunction steeringEnvelope(snapshot: SteeringSnapshot): string {\n const plan = snapshot.plan\n ? `Source: ${snapshot.plan.path}\\n\\n${snapshot.plan.content}`\n : '(no active plan document)';\n const importantContext = [\n snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(', ')}` : undefined,\n snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(', ')}` : undefined,\n ].filter((value): value is string => Boolean(value));\n\n return `<compaction-steering priority=\"user,plan,context-contributions,important-context,recent-messages\">\n<user-prompt source=\"conversation\">\nTreat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.\n</user-prompt>\n<active-plan>\n${plan}\n</active-plan>\n<context-contributions>\n${formatContextContributions(snapshot.contextContributions)}\n</context-contributions>\n<important-context>\n${importantContext.length > 0 ? importantContext.join('\\n') : '(none recorded outside the conversation)'}\n</important-context>\n</compaction-steering>`;\n}\n\nexport function checkpointInstructions(pass: AutocompactPass, steering: SteeringSnapshot): string {\n const decision =\n pass === 2\n ? 'Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.\\n\\n'\n : '';\n\n // Summarization is a tool-less single LLM call, so instructions describe only what to\n // produce. Directives aimed at an implementing agent leak into the checkpoint body.\n return `Create Po autocompact checkpoint pass ${pass}.\n\n${steeringEnvelope(steering)}\n\nApply the steering evidence in priority order. Do not invent plan or contributed runtime state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.\n\n${decision}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.\n\n## Goal\n## Constraints & Preferences\n## Progress\n### Done\n### In Progress\n### Blocked\n## Key Decisions\n## Next Steps\n## Critical Context`;\n}\n\ninterface AutocompactRuntimeConfig {\n /** Off leaves compaction to the host; unset is on. */\n enabled: boolean;\n /** The agent that writes the summaries, from autocompact's own keys or planning's. */\n agent?: PlanningAgentConfig;\n ratios: AutocompactRatioOverrides;\n /** Per-model absolute token checkpoints, tried in file order. */\n overrides: AutocompactOverrideConfig[];\n}\n\nconst DEFAULT_RUNTIME_CONFIG: AutocompactRuntimeConfig = { enabled: true, ratios: {}, overrides: [] };\n\n/**\n * What the Po config says about this package.\n *\n * `modes.autocompact` is read first and `modes.planning.subagents` is the\n * fallback, because summarization borrowed the planning subagent model before\n * it had keys of its own and existing files still spell it that way.\n */\nexport function autocompactRuntimeConfig(\n root: string,\n onLoadFailure?: (error: unknown) => void,\n): AutocompactRuntimeConfig {\n let modes: ReturnType<typeof loadPoConfig>['modes'];\n try {\n modes = loadPoConfig(root).modes;\n } catch (error) {\n process.emitWarning('Po autocompact configuration could not be loaded; using the active session model instead.');\n onLoadFailure?.(error);\n return DEFAULT_RUNTIME_CONFIG;\n }\n const configured = modes?.autocompact;\n const ownAgent: PlanningAgentConfig | undefined =\n configured && (configured.model !== undefined || configured.thinking !== undefined)\n ? {\n ...(configured.model ? { model: configured.model } : {}),\n ...(configured.thinking ? { thinking: configured.thinking } : {}),\n }\n : undefined;\n const agent = ownAgent ?? modes?.planning?.subagents;\n const thresholds = configured?.thresholds;\n return {\n enabled: configured?.enabled ?? true,\n ...(agent ? { agent } : {}),\n ratios: {\n ...(thresholds?.pass1 === undefined ? {} : { 1: thresholds.pass1 }),\n ...(thresholds?.pass2 === undefined ? {} : { 2: thresholds.pass2 }),\n ...(thresholds?.pass3 === undefined ? {} : { 3: thresholds.pass3 }),\n },\n overrides: configured?.overrides ?? [],\n };\n}\n","import {\n ArtifactAccessError,\n COMPACTION_ARTIFACT_DIRECTORY,\n listArtifacts,\n openArtifact,\n readArtifactBytes,\n removeArtifact,\n writeArtifactText,\n} from '@agimon-ai/po-artifact/artifactFiles';\n\nimport { CHECKPOINT_MESSAGE_TYPE, CONTEXT_MESSAGE_TYPE } from '../../constants/autocompact';\nimport {\n checkpointSummaryFromEntry,\n contextDetailsFromUnknown,\n customMessage,\n type CompactionPolicyEntry,\n} from '../compactionPolicy';\nimport type { CompactionHistoryFile } from './type';\n\nconst FORMAT = 'po-compaction/1';\nconst HEADER = `---\\nformat: ${JSON.stringify(FORMAT)}\\n`;\nconst HISTORY_PATH = new RegExp(\n `^${COMPACTION_ARTIFACT_DIRECTORY}/(?:epoch-\\\\d+/(?:summary|checkpoint-\\\\d+)|in-epoch/checkpoint-\\\\d+)\\\\.md$`,\n);\n// Native compaction wraps its summary this way (pi-durable dist/harness/compaction.js, po-core piMessages).\nconst NATIVE_PREFIX =\n 'The conversation history before this point was compacted into the following summary:\\n\\n<summary>\\n';\nconst NATIVE_SUFFIX = '\\n</summary>';\n\ntype HistoryFields = Record<string, string | number | undefined>;\n\nfunction historyFile(path: string, fields: HistoryFields, body: string): CompactionHistoryFile {\n const header = Object.entries({ format: FORMAT, ...fields }).flatMap(([key, value]) =>\n value === undefined ? [] : [`${key}: ${JSON.stringify(value)}`],\n );\n return { path: `${COMPACTION_ARTIFACT_DIRECTORY}/${path}`, text: `---\\n${header.join('\\n')}\\n---\\n\\n${body}\\n` };\n}\n\nfunction isoTime(value: string | number): string | undefined {\n const time = new Date(value);\n return Number.isFinite(time.getTime()) ? time.toISOString() : undefined;\n}\n\nfunction passOf(value: unknown): number | undefined {\n if (typeof value !== 'object' || value === null || !('pass' in value)) return undefined;\n return value.pass === 1 || value.pass === 2 || value.pass === 3 ? value.pass : undefined;\n}\n\nfunction committedFields(entry: CompactionPolicyEntry): { body: string; fields: HistoryFields } | undefined {\n if (entry.type === 'compaction') {\n const summary = entry.summary.trim();\n const body =\n summary.startsWith(NATIVE_PREFIX) && summary.endsWith(NATIVE_SUFFIX)\n ? summary.slice(NATIVE_PREFIX.length, -NATIVE_SUFFIX.length).trim()\n : summary;\n return {\n body,\n fields: { source: 'compact', tokensBefore: entry.tokensBefore > 0 ? entry.tokensBefore : undefined },\n };\n }\n const marker = customMessage(entry);\n const details = marker?.customType === CONTEXT_MESSAGE_TYPE ? contextDetailsFromUnknown(marker.details) : undefined;\n if (!details) return undefined;\n return {\n body: checkpointSummaryFromEntry(entry) ?? '',\n fields: {\n source: 'autocompact',\n pass: details.poAutocompact.pass,\n tokensBefore: details.poAutocompact.tokensBefore,\n },\n };\n}\n\n/** The only entries `wantedHistory` reads, so mirrors can scan history without keeping the rest. */\nexport function isHistoryEntry(entry: CompactionPolicyEntry): boolean {\n const type = customMessage(entry)?.customType;\n return (\n entry.type === 'compaction' ||\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n type === CHECKPOINT_MESSAGE_TYPE ||\n type === CONTEXT_MESSAGE_TYPE\n );\n}\n\n/** Number commits along the active branch so a rewind rewrites the same epoch folders. */\nexport function wantedHistory(entries: readonly CompactionPolicyEntry[]): CompactionHistoryFile[] {\n const files: CompactionHistoryFile[] = [];\n let staged: Array<{ entry: CompactionPolicyEntry; summary: string; pass: number | undefined }> = [];\n let epoch = 1;\n const checkpoints = (folder: string) =>\n staged.map(({ entry, summary, pass }, index) =>\n historyFile(\n `${folder}/checkpoint-${index + 1}.md`,\n {\n kind: 'checkpoint',\n epoch,\n checkpoint: index + 1,\n entryId: entry.id,\n source: 'autocompact',\n pass,\n timestamp: isoTime(entry.timestamp),\n },\n summary,\n ),\n );\n for (const entry of entries) {\n const marker = customMessage(entry);\n if (\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n marker?.customType === CHECKPOINT_MESSAGE_TYPE\n ) {\n const summary = checkpointSummaryFromEntry(entry);\n if (summary)\n staged.push({ entry, summary, pass: passOf(entry.type === 'custom' ? entry.data : marker?.details) });\n continue;\n }\n const committed = committedFields(entry);\n if (!committed) continue;\n files.push(\n ...checkpoints(`epoch-${epoch}`),\n historyFile(\n `epoch-${epoch}/summary.md`,\n { kind: 'summary', epoch, entryId: entry.id, ...committed.fields, timestamp: isoTime(entry.timestamp) },\n committed.body,\n ),\n );\n staged = [];\n epoch += 1;\n }\n files.push(...checkpoints('in-epoch'));\n return files;\n}\n\nasync function ownedHistory(root: string, path: string): Promise<boolean> {\n const file = await openArtifact(root, path).catch((error: unknown) => {\n // Gone since the listing: nothing left to prune.\n if (error instanceof ArtifactAccessError && error.status === 404) return undefined;\n throw error;\n });\n if (!file) return false;\n try {\n const bytes = await readArtifactBytes(file.handle, Math.min(file.stat.size, HEADER.length));\n return new TextDecoder().decode(bytes) === HEADER;\n } finally {\n await file.handle.close();\n }\n}\n\n/** Mirror history into the session artifact folder. Pruning touches only files carrying this mirror's header. */\nexport async function mirrorCompactionHistory(root: string, entries: readonly CompactionPolicyEntry[]): Promise<void> {\n const files = wantedHistory(entries);\n // ponytail: rewinding to before the first checkpoint keeps the old files; prune on empty if that ever misleads.\n if (files.length === 0) return;\n for (const file of files) await writeArtifactText(root, file.path, file.text);\n const listed = await listArtifacts(root);\n if (listed.error) throw new Error(listed.error);\n const wanted = new Set(files.map((file) => file.path));\n const stale = listed.items.filter((item) => HISTORY_PATH.test(item.path) && !wanted.has(item.path));\n for (const item of stale) if (await ownedHistory(root, item.path)) await removeArtifact(root, item.path);\n for (const folder of new Set(stale.map((item) => item.path.slice(0, item.path.lastIndexOf('/')))))\n await removeArtifact(root, folder);\n}\n","/**\n * Picks the absolute token checkpoints configured for the model a session is running.\n *\n * DESIGN PATTERNS:\n * - Pure decision function, so the matching rule is unit-testable without a session,\n * a config file or a filesystem\n * - First match in file order wins, so a reader resolves a model by reading down the\n * list rather than by working out which pattern is the most specific\n * - A model matching nothing returns no overrides at all, which leaves the ratio\n * ladder exactly as it behaves without this feature\n *\n * AVOID:\n * - Stripping a thinking suffix the way subagent model scope does. That matches\n * free-typed config strings; this matches a resolved `Model`, whose `id` carries\n * the level in a separate field and never in the id itself.\n * - Matching a bare pattern against `provider/id`. The glob wildcard does not cross\n * the separator, so the subject has to follow the pattern's own shape.\n */\n\nimport type { AutocompactOverrideConfig } from '@agimon-ai/po-config';\nimport { minimatch } from 'minimatch';\n\nimport type { AutocompactTokenOverrides } from '../../types/autocompact';\n\n/** The parts of a resolved model the rules match on. */\nexport interface AutocompactModelIdentity {\n id: string;\n provider: string;\n}\n\n/**\n * A pattern naming a provider is matched against `provider/id`, anything else\n * against the bare id. `*` does not cross `/`, so a bare pattern tested against a\n * qualified subject would never match and would read as a silently dead rule.\n */\nfunction matchesModelPattern(pattern: string, model: AutocompactModelIdentity): boolean {\n const subject = pattern.includes('/') ? `${model.provider}/${model.id}` : model.id;\n return minimatch(subject, pattern, { nocase: true });\n}\n\nexport function resolveModelTokenOverrides(\n model: AutocompactModelIdentity | undefined,\n overrides: readonly AutocompactOverrideConfig[],\n): AutocompactTokenOverrides {\n if (!model) return {};\n const matched = overrides.find((entry) => matchesModelPattern(entry.model, model));\n if (!matched) return {};\n const { pass1, pass2, pass3 } = matched.tokens;\n return {\n ...(pass1 === undefined ? {} : { 1: pass1 }),\n ...(pass2 === undefined ? {} : { 2: pass2 }),\n ...(pass3 === undefined ? {} : { 3: pass3 }),\n };\n}\n","import type { ExtensionContext } from '@earendil-works/pi-coding-agent';\n\nconst THINKING_SUFFIX_PATTERN = /:(off|minimal|low|medium|high|xhigh|max)$/;\n\nexport interface SummarizationModel {\n model: NonNullable<ExtensionContext['model']>;\n thinkingLevel?: NonNullable<ExtensionContext['thinkingLevel']>;\n}\n\nexport interface ModelReference {\n provider: string;\n modelId: string;\n thinking?: NonNullable<ExtensionContext['thinkingLevel']>;\n}\n\n/** Splits a `provider/model` reference, tolerating the optional thinking suffix. */\nexport function parseModelReference(reference: string): ModelReference | undefined {\n const trimmed = reference.trim();\n const thinking = THINKING_SUFFIX_PATTERN.exec(trimmed)?.[1] as SummarizationModel['thinkingLevel'];\n const identity = trimmed.replace(THINKING_SUFFIX_PATTERN, '');\n const separator = identity.indexOf('/');\n if (separator <= 0 || separator >= identity.length - 1) return undefined;\n return {\n provider: identity.slice(0, separator),\n modelId: identity.slice(separator + 1),\n ...(thinking ? { thinking } : {}),\n };\n}\n","import { artifactRoot } from '@agimon-ai/po-artifact/artifactFiles';\nimport {\n PO_CONTEXT_CONTRIBUTIONS_SERVICE,\n requirePoContextContributions,\n type PoContextContributionsService,\n} from '@agimon-ai/po-core/contextContributions';\nimport type { PoFooterContributionHandle } from '@agimon-ai/po-core/footer';\nimport type { PoHeadlessExecutionContext, PoHeadlessHook } from '@agimon-ai/po-core/headless';\nimport { PO_UI_HUB_SERVICE, requirePoUiHub } from '@agimon-ai/po-core/uiHub';\n\nimport {\n CHECKPOINT_MESSAGE_TYPE,\n CONTEXT_MESSAGE_TYPE,\n MAX_INVALID_CHECKPOINT_ATTEMPTS,\n RESUME_MESSAGE_TYPE,\n RUNTIME_STATE_MESSAGE_TYPE,\n STATE_CUSTOM_TYPE,\n STATE_VERSION,\n} from '../../constants/autocompact';\nimport {\n FOOTER_ORDER,\n FOOTER_SOURCE,\n PLAN_DOCUMENT_ENTRY,\n SLOW_CONTEXT_HOOK_MS,\n STATUS_KEY,\n} from '../../constants/runtime';\nimport type { AutocompactContextDetails, AutocompactMessage, AutocompactState } from '../../types/autocompact';\nimport {\n autocompactRuntimeConfig,\n checkpointInstructions,\n formatRuntimeState,\n latestPlanSnapshot,\n readContextContributionsSnapshot,\n runtimeStateSnapshot,\n} from '../autocompactRuntime';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from '../autocompactTelemetry';\nimport { isHistoryEntry, mirrorCompactionHistory } from '../compactionHistory';\nimport {\n baselineUsageIsSettled,\n checkpointRequestDetails,\n checkpointSummaryFromEntry,\n contextDetailsFromUnknown,\n createInitialState,\n createRequestId,\n customMessage,\n effectiveThresholds,\n fileDetailsFromUnknown,\n fileOperationsFromMessages,\n isStructuredCheckpoint,\n latestCheckpointArtifactEntry,\n mergeFileDetails,\n parseCheckpointDecision,\n parseState,\n projectContextMessages,\n withCanonicalFileSections,\n type CompactionPolicyEntry,\n} from '../compactionPolicy';\nimport { resolveModelTokenOverrides } from '../modelOverrides';\nimport { parseModelReference } from '../summarizationModel';\nimport type { NativeAutocompactDependencies, NativeAutocompactRuntime } from './type';\n\n/** Exact canonical-prefix comparison refuses to apply summaries to edited or replaced evidence. */\nfunction tailAfter(\n snapshot: readonly AutocompactMessage[],\n current: readonly AutocompactMessage[],\n): AutocompactMessage[] | undefined {\n if (\n snapshot.length > current.length ||\n snapshot.some((message, index) => JSON.stringify(message) !== JSON.stringify(current[index]))\n )\n return undefined;\n return current.slice(snapshot.length);\n}\n\nfunction leaf(entries: readonly CompactionPolicyEntry[]): string {\n return (\n entries.findLast(\n (entry) =>\n entry.type !== 'custom' ||\n (entry.customType !== STATE_CUSTOM_TYPE && entry.customType !== CHECKPOINT_MESSAGE_TYPE),\n )?.id ?? 'root'\n );\n}\n\nexport function createNativeAutocompact(dependencies: NativeAutocompactDependencies = {}): NativeAutocompactRuntime {\n const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();\n let active = true;\n let generation = 0;\n let state: AutocompactState = createInitialState();\n let snapshot: AutocompactMessage[] | undefined;\n let previousSnapshot: AutocompactMessage[] | undefined;\n let context: PoHeadlessExecutionContext | undefined;\n let contributions: PoContextContributionsService | undefined;\n let controller: AbortController | undefined;\n let serial: Promise<void> = Promise.resolve();\n const work = new Set<Promise<void>>();\n const applied = new Set<string>();\n const invalid = new Set<string>();\n let configFailureReported = false;\n let footer: PoFooterContributionHandle | undefined;\n let navigating = false;\n let degraded = false;\n let lastNativeCompactionId: string | undefined;\n let checkpointBoundary:\n | ReturnType<NonNullable<PoHeadlessExecutionContext['session']['registerCheckpointBoundary']>>\n | undefined;\n let mirrorQueued = false;\n let historyWarnedSession: string | undefined;\n\n const attributes = () => ({\n 'pi.session.id': context?.sessionId ?? '',\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': state.pass,\n ...(state.requestId ? { 'autocompact.request.id': state.requestId } : {}),\n ...(state.snapshotLeafId ? { 'autocompact.snapshot_leaf_id': state.snapshotLeafId } : {}),\n ...(state.snapshotTokens === undefined ? {} : { 'autocompact.tokens_before': state.snapshotTokens }),\n });\n const configured = (execution: PoHeadlessExecutionContext) =>\n autocompactRuntimeConfig(execution.repoRoot, (error) => {\n if (!configFailureReported) {\n configFailureReported = true;\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.configurationLoadFailed, error, {\n ...attributes(),\n 'failure.kind': 'configuration',\n });\n }\n });\n const alive = (version: number) => active && !navigating && generation === version;\n const refreshStatus = (execution: PoHeadlessExecutionContext) => {\n const phase =\n state.phase === 'checkpoint_pending'\n ? 'summarizing'\n : state.phase === 'checkpoint_ready'\n ? 'applying'\n : undefined;\n footer?.update(phase ? { fullText: `Compacting p${state.pass}`, compactText: `C${state.pass}` } : undefined);\n execution.client.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : undefined);\n };\n const enqueue = (callback: () => Promise<void>): Promise<void> => {\n const version = generation;\n const operation = serial.then(async () => {\n if (alive(version)) await callback();\n });\n serial = operation.catch(() => undefined);\n return operation;\n };\n const persist = async (execution: PoHeadlessExecutionContext, version: number) => {\n if (!alive(version)) return;\n await execution.session.appendCustomEntry(STATE_CUSTOM_TYPE, {\n ...state,\n nativeLastCompactionId: lastNativeCompactionId,\n });\n if (alive(version)) refreshStatus(execution);\n };\n const clear = () => {\n delete state.requestId;\n delete state.snapshotLeafId;\n delete state.snapshotTokens;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n snapshot = undefined;\n };\n const fail = async (\n execution: PoHeadlessExecutionContext,\n version: number,\n error: unknown,\n malformed = false,\n kind:\n | 'empty_checkpoint'\n | 'evidence_changed'\n | 'configuration'\n | 'persistence'\n | 'validation'\n | 'unknown' = 'unknown',\n ) => {\n if (!alive(version)) return;\n degraded = true;\n const eventAttributes = attributes();\n const attempts = state.invalidAttempts + 1;\n const pass = state.pass;\n const failedLeaf = state.snapshotLeafId;\n state.invalidAttempts += 1;\n if (state.invalidAttempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS) {\n state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);\n state.exhaustedPasses.push(pass);\n state.invalidAttempts = 0;\n }\n state.phase = 'waiting';\n clear();\n state.lastAttemptLeafId = failedLeaf;\n const errors = [error];\n try {\n await persist(execution, version);\n } catch (persistError) {\n errors.push(persistError);\n }\n if (!alive(version)) return;\n // Reporting is best effort: neither sink may prevent recovery or the native-compaction fallback.\n await Promise.allSettled([\n Promise.resolve().then(() =>\n execution.client.notify({\n body: `Po autocompact summarization pass ${pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n level: 'error',\n }),\n ),\n ...errors.map((failure, index) =>\n Promise.resolve().then(() =>\n telemetry.recordError(\n malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed,\n failure,\n {\n ...eventAttributes,\n 'failure.kind': index === 0 ? kind : 'persistence',\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS,\n },\n // The summarizer's failure is the only clue to why a pass failed; the sink redacts secrets.\n { includeException: true },\n ),\n ),\n ),\n ]);\n };\n // Stream history newest first, keeping only matching entries (oldest first), so large custom journals never pile up.\n const matching = async (\n execution: PoHeadlessExecutionContext,\n keep: (entry: CompactionPolicyEntry) => boolean,\n stopAt?: string,\n ) => {\n const entries: CompactionPolicyEntry[] = [];\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n if (entry.id === stopAt) break;\n if (keep(entry)) entries.push(entry);\n }\n return entries.reverse();\n };\n // Snapshot metadata can precede the context boundary: read only the newest plan and, when asked, checkpoint artifact.\n const policyEntries = async (execution: PoHeadlessExecutionContext, withCheckpoint: boolean) => {\n const entries = [\n ...(await execution.session.entries({\n type: 'custom',\n customType: PLAN_DOCUMENT_ENTRY,\n limit: 1,\n })),\n ] as unknown as CompactionPolicyEntry[];\n if (withCheckpoint) {\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n if (!latestCheckpointArtifactEntry([entry])) continue;\n entries.push(entry);\n break;\n }\n }\n return entries;\n };\n const contextBranch = async (execution: PoHeadlessExecutionContext) => {\n const entries: CompactionPolicyEntry[] = [];\n let foundLeaf = false;\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n const isLeaf = leaf([entry]) !== 'root';\n // Custom journals do not contribute model context. Keep only the newest leaf identity.\n if (entry.type !== 'custom' || (!foundLeaf && isLeaf)) entries.push(entry);\n if (isLeaf) foundLeaf = true;\n if (entry.type === 'compaction' || customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE) break;\n }\n return entries.reverse();\n };\n const canonical = async (execution: PoHeadlessExecutionContext, entries: CompactionPolicyEntry[]) => {\n if (!execution.session.contextMessages) throw new Error('Canonical context is unavailable for autocompact.');\n return projectContextMessages(\n (await execution.session.contextMessages()) as unknown as AutocompactMessage[],\n entries,\n ).messages;\n };\n // History is a convenience copy: its failure is reported once per session and never touches compaction state.\n // Never await this inside a queued job; it queues behind the job that schedules it.\n const scheduleMirror = (execution: PoHeadlessExecutionContext) => {\n if (mirrorQueued) return;\n mirrorQueued = true;\n void enqueue(async () => {\n mirrorQueued = false;\n try {\n await mirrorCompactionHistory(\n artifactRoot(execution.sessionId, execution.environment),\n await matching(execution, isHistoryEntry),\n );\n } catch (error) {\n const warn = historyWarnedSession !== execution.sessionId;\n historyWarnedSession = execution.sessionId;\n await Promise.allSettled([\n Promise.resolve().then(() =>\n telemetry.recordWarning(AUTOCOMPACT_EVENT.historyWriteFailed, error, attributes()),\n ),\n ...(warn\n ? [\n Promise.resolve().then(() =>\n execution.client.notify({\n body: `Po autocompact could not save compaction history: ${error instanceof Error ? error.message : String(error)}`,\n level: 'warning',\n }),\n ),\n ]\n : []),\n ]);\n }\n }).finally(() => {\n mirrorQueued = false;\n });\n };\n const contributionSnapshot = async (execution: PoHeadlessExecutionContext) => {\n const result = readContextContributionsSnapshot(contributions);\n for (const error of result.errors) {\n await execution.client.notify({\n body: `Po autocompact context contribution degraded (${error.source}/${error.id}): ${error.message}`,\n level: 'warning',\n });\n await telemetry.recordWarning(AUTOCOMPACT_EVENT.contextContributionDegraded, new Error(error.message), {\n ...attributes(),\n 'autocompact.context_contribution.source': error.source,\n 'autocompact.context_contribution.id': error.id,\n 'autocompact.context_contribution.order': error.order,\n });\n }\n return result;\n };\n const runtimeState = async (\n execution: PoHeadlessExecutionContext,\n entries: CompactionPolicyEntry[],\n version: number,\n appendMessage: PoHeadlessExecutionContext['session']['appendMessage'] = checkpointBoundary?.appendMessage.bind(\n checkpointBoundary,\n ),\n ) => {\n const saved = runtimeStateSnapshot(entries, await contributionSnapshot(execution));\n if (!alive(version)) return;\n await appendMessage?.({\n type: RUNTIME_STATE_MESSAGE_TYPE,\n text: formatRuntimeState(saved),\n display: false,\n details: { version: 2, ...saved },\n });\n return {\n 'autocompact.runtime.plan_present': Boolean(saved.planPath),\n 'autocompact.runtime.contribution_count': saved.contributions.length,\n 'autocompact.runtime.contribution_error_count': saved.contributionErrors.length,\n };\n };\n const summaryModel = async (execution: PoHeadlessExecutionContext, configuration: ReturnType<typeof configured>) => {\n const ownReference = configuration.agent?.model ? parseModelReference(configuration.agent.model) : undefined;\n const candidate = ownReference ? `${ownReference.provider}/${ownReference.modelId}` : undefined;\n const reference =\n candidate && execution.textCompletion!.available(candidate)\n ? candidate\n : execution.model\n ? `${execution.model.provider}/${execution.model.id}`\n : '';\n const thinking =\n configuration.agent?.thinking ??\n (reference === candidate ? ownReference?.thinking : undefined) ??\n (await execution.session.readModelSettings?.())?.thinkingLevel;\n return { reference, thinking };\n };\n // Manual compaction summarizes stored entries, which still hold everything this extension only projected away.\n // Commit a checkpoint now instead, folding what arrived since this cycle's staged summary the way pass 3 does.\n const manualCompaction = async (event: { instructions?: unknown }, execution: PoHeadlessExecutionContext) => {\n const configuration = configured(execution);\n if (!configuration.enabled || !execution.textCompletion?.summarize) return;\n try {\n const entries = await contextBranch(execution);\n const pinned = await policyEntries(execution, state.pass > 1);\n const messages = await canonical(execution, entries);\n const delta = state.pass > 1 && previousSnapshot ? tailAfter(previousSnapshot, messages) : undefined;\n const previous = state.pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(pinned)) : undefined;\n const { reference, thinking } = await summaryModel(execution, configuration);\n const instructions = checkpointInstructions(3, {\n plan: latestPlanSnapshot(pinned),\n contextContributions: await contributionSnapshot(execution),\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n });\n const { summary } = parseCheckpointDecision(\n await execution.textCompletion.summarize(reference, {\n messages: (delta ?? messages) as unknown as Record<string, unknown>[],\n instructions:\n typeof event.instructions === 'string' && event.instructions.trim()\n ? `${instructions}\\n\\n${event.instructions}`\n : instructions,\n ...(previous ? { previousSummary: previous } : {}),\n ...(thinking ? { thinkingLevel: thinking } : {}),\n ...(execution.signal ? { signal: execution.signal } : {}),\n }),\n );\n if (!isStructuredCheckpoint(summary)) throw new Error('Summarization returned an incomplete checkpoint.');\n const files = mergeFileDetails(state, fileOperationsFromMessages(messages));\n const usage = await execution.session.contextUsage?.();\n return {\n compaction: {\n summary: withCanonicalFileSections(summary, files),\n tokensBefore: usage?.tokens ?? 0,\n retainedTail: [],\n details: files,\n },\n };\n } catch (error) {\n // The host falls back to native compaction, whose own failure would hide this reason.\n await execution.client.notify({\n body: `Po autocompact manual compaction failed: ${error instanceof Error ? error.message : String(error)}`,\n level: 'error',\n });\n throw error;\n }\n };\n const resetCycle = () => {\n state.phase = 'waiting';\n state.checkpointQueue = [];\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n state.baselinePending = true;\n state.cycle += 1;\n state.pass = 1;\n delete state.lastAttemptLeafId;\n delete state.latestCheckpointSnapshotLeafId;\n clear();\n previousSnapshot = undefined;\n };\n const applyReady = async (\n execution: PoHeadlessExecutionContext,\n version: number,\n appendMessage: NonNullable<typeof checkpointBoundary>['appendMessage'],\n ): Promise<boolean> => {\n if (state.phase !== 'checkpoint_ready' || !state.pendingCheckpoint || !state.requestId || !state.snapshotLeafId)\n return false;\n const decision = parseCheckpointDecision(state.pendingCheckpoint);\n if (!isStructuredCheckpoint(decision.summary)) {\n await fail(execution, version, new Error('Summarization returned an incomplete checkpoint.'), true, 'validation');\n return false;\n }\n const entries = await contextBranch(execution);\n const messages = await canonical(execution, entries);\n if (!alive(version)) return false;\n // Persisted legacy pending summaries lack canonical evidence. Retry rather than fabricate a retained tail.\n const tail = snapshot && tailAfter(snapshot, messages);\n if (!tail) {\n await fail(\n execution,\n version,\n new Error('Canonical checkpoint evidence changed; summary must be regenerated.'),\n false,\n 'evidence_changed',\n );\n return false;\n }\n const pass = state.pass;\n if (pass === 1 || (pass === 2 && decision.shouldCompact !== true)) {\n await execution.session.appendCustomEntry(CHECKPOINT_MESSAGE_TYPE, {\n ...checkpointRequestDetails(state.cycle, pass, state.requestId),\n summary: decision.summary,\n });\n if (!alive(version)) return false;\n previousSnapshot = snapshot;\n state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;\n state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);\n state.pass = pass === 1 ? 2 : 3;\n state.phase = 'waiting';\n state.invalidAttempts = 0;\n clear();\n await persist(execution, version);\n scheduleMirror(execution);\n return false;\n }\n const files = mergeFileDetails(state, fileOperationsFromMessages(messages));\n const details: AutocompactContextDetails = {\n ...files,\n poAutocompact: {\n version: STATE_VERSION,\n cycle: state.cycle,\n pass,\n requestId: state.requestId,\n snapshotLeafId: state.snapshotLeafId,\n tokensBefore: state.snapshotTokens ?? 0,\n },\n retainedMessages: tail,\n };\n const idle = (await execution.session.activity()).isIdle;\n if (!alive(version)) return false;\n // The marker heads native context, so native compaction and context reads skip everything before it.\n const id = await appendMessage(\n {\n type: CONTEXT_MESSAGE_TYPE,\n text: withCanonicalFileSections(decision.summary, files),\n display: false,\n details,\n },\n { resetContext: { retainedMessages: tail as unknown as Record<string, unknown>[] } },\n );\n if (!alive(version) || !id) return false;\n await execution.session.setLabel?.(id, `autocompact:c${state.cycle}:p${pass}`);\n if (!alive(version)) return false;\n const runtimeAttributes = await runtimeState(\n execution,\n await policyEntries(execution, false),\n version,\n appendMessage,\n );\n if (!alive(version)) return false;\n const committedAttributes = attributes();\n state.readFiles = files.readFiles;\n state.modifiedFiles = files.modifiedFiles;\n resetCycle();\n await persist(execution, version);\n scheduleMirror(execution);\n if (!alive(version)) return false;\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextCommitted, {\n ...committedAttributes,\n 'autocompact.message_count.before': messages.length,\n 'autocompact.message_count.retained': tail.length,\n 'autocompact.apply_mode': idle ? 'idle' : 'turn_end',\n ...runtimeAttributes,\n });\n if (idle && alive(version))\n await execution.session.admitPrompt?.(\n \"Asynchronous compaction completed. Continue from the compacted checkpoint's immediate next action without repeating completed work.\",\n 'steer',\n undefined,\n `${RESUME_MESSAGE_TYPE}:${details.poAutocompact.requestId}`,\n );\n return true;\n };\n const ensureCheckpointBoundary = (execution: PoHeadlessExecutionContext) => {\n if (checkpointBoundary) return;\n if (!execution.session.registerCheckpointBoundary) throw new Error('Native checkpoint boundaries are unavailable.');\n checkpointBoundary = execution.session.registerCheckpointBoundary(async (boundary) => {\n if (!active || navigating || boundary.signal?.aborted) return;\n const current = context ?? execution;\n await enqueue(() =>\n boundary.signal?.aborted ? Promise.resolve() : progress(current, true, boundary.appendMessage.bind(boundary)),\n );\n });\n };\n const advance = async (\n execution: PoHeadlessExecutionContext,\n allowBusy = false,\n appendMessage = checkpointBoundary?.appendMessage.bind(checkpointBoundary),\n ) => {\n const version = generation;\n context = execution;\n const activity = await execution.session.activity();\n if (!alive(version) || activity.hasPendingMessages) return;\n if (appendMessage && (activity.isIdle || allowBusy)) {\n if (await applyReady(execution, version, appendMessage)) return;\n }\n if (!alive(version) || state.phase !== 'waiting') return;\n const configuration = configured(execution);\n if (!configuration.enabled || !execution.session.contextUsage || !execution.textCompletion?.summarize) return;\n const usage = await execution.session.contextUsage();\n if (\n !alive(version) ||\n !usage ||\n typeof usage.tokens !== 'number' ||\n !Number.isFinite(usage.tokens) ||\n usage.tokens < 0\n )\n return;\n const tokens = usage.tokens;\n const thresholds = effectiveThresholds(\n usage.contextWindow,\n state.baselineTokens,\n configuration.ratios,\n resolveModelTokenOverrides(execution.model, configuration.overrides),\n );\n if (\n !state.baselinePending &&\n !state.checkpointQueue.length &&\n !([1, 2, 3] as const).some(\n (pass) => pass >= state.pass && !state.exhaustedPasses.includes(pass) && tokens >= thresholds[pass],\n )\n )\n return;\n const entries = await contextBranch(execution);\n if (!alive(version)) return;\n if (state.baselinePending) {\n if (!baselineUsageIsSettled(entries)) return;\n state.baselineTokens = usage.tokens;\n state.baselinePending = false;\n await persist(execution, version);\n return;\n }\n const currentLeaf = leaf(entries);\n if (currentLeaf === state.lastAttemptLeafId) return;\n for (const pass of [1, 2, 3] as const) {\n if (\n pass >= state.pass &&\n !state.checkpointQueue.includes(pass) &&\n !state.exhaustedPasses.includes(pass) &&\n usage.tokens >= thresholds[pass]\n )\n state.checkpointQueue.push(pass);\n }\n const pass = state.checkpointQueue[0];\n if (!pass) return;\n state.pass = pass;\n const checkpointEntries = await policyEntries(execution, pass > 1);\n const messages = await canonical(execution, entries);\n const steering = await contributionSnapshot(execution);\n if (!alive(version)) return;\n snapshot = messages;\n const previous =\n pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(checkpointEntries)) : undefined;\n const requestId = createRequestId(execution.sessionId, state.cycle, pass, currentLeaf);\n state.phase = 'checkpoint_pending';\n state.requestId = requestId;\n state.snapshotLeafId = currentLeaf;\n state.snapshotTokens = usage.tokens;\n delete state.lastAttemptLeafId;\n delete state.pendingCheckpoint;\n await persist(execution, version);\n if (!alive(version)) return;\n degraded = false;\n controller?.abort();\n controller = new AbortController();\n const signal = controller.signal;\n const requestAttributes = { ...attributes(), 'autocompact.message_count.before': messages.length };\n const delta = previousSnapshot ? tailAfter(previousSnapshot, messages) : undefined;\n let failureKind: 'configuration' | 'unknown' | 'persistence' = 'configuration';\n const completion = telemetry\n .runInSpan('po_autocompact.checkpoint', requestAttributes, async () => {\n const { reference, thinking } = await summaryModel(execution, configuration);\n failureKind = 'unknown';\n if (!alive(version) || signal.aborted) return '';\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, requestAttributes);\n return execution.textCompletion!.summarize!(reference, {\n messages: (pass > 1 && delta ? delta : messages) as unknown as Record<string, unknown>[],\n instructions: checkpointInstructions(pass, {\n plan: latestPlanSnapshot(checkpointEntries),\n contextContributions: steering,\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n }),\n ...(previous ? { previousSummary: previous } : {}),\n ...(thinking ? { thinkingLevel: thinking } : {}),\n signal,\n });\n })\n .then(async (summary) => {\n await enqueue(async () => {\n if (!alive(version) || signal.aborted || state.requestId !== requestId) return;\n if (!summary.trim()) {\n await fail(\n execution,\n version,\n new Error('Summarization returned an empty checkpoint.'),\n false,\n 'empty_checkpoint',\n );\n return;\n }\n state.phase = 'checkpoint_ready';\n state.pendingCheckpoint = summary.trim();\n failureKind = 'persistence';\n await persist(execution, version);\n failureKind = 'unknown';\n if (!alive(version)) return;\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {\n ...requestAttributes,\n 'autocompact.checkpoint.characters': summary.length,\n });\n if ((await execution.session.activity()).isIdle && alive(version)) await progress(execution);\n });\n })\n .catch(async (error: unknown) => {\n await enqueue(async () => {\n if (alive(version) && state.requestId === requestId)\n await fail(execution, version, error, false, failureKind);\n });\n });\n work.add(completion);\n void completion.then(\n () => work.delete(completion),\n () => work.delete(completion),\n );\n };\n const progress = async (\n execution: PoHeadlessExecutionContext,\n allowBusy = false,\n appendMessage?: Parameters<typeof advance>[2],\n ) => {\n const version = generation;\n try {\n ensureCheckpointBoundary(execution);\n await advance(execution, allowBusy, appendMessage);\n } catch (error) {\n try {\n await fail(execution, version, error, false, 'persistence');\n } finally {\n // Infrastructure failures can recover without a new conversation leaf.\n if (alive(version)) delete state.lastAttemptLeafId;\n }\n }\n };\n const load = async (execution: PoHeadlessExecutionContext) => {\n if (!active) return;\n navigating = false;\n generation += 1;\n const version = generation;\n controller?.abort(new Error('Autocompact session generation changed.'));\n controller = undefined;\n context = execution;\n applied.clear();\n invalid.clear();\n const saved = await execution.session.customSnapshot?.(STATE_CUSTOM_TYPE);\n if (!alive(version)) return;\n const entry = (saved?.available ? saved.entry : undefined) as unknown as CompactionPolicyEntry | undefined;\n const data =\n entry?.type === 'custom' && entry.data && typeof entry.data === 'object'\n ? (entry.data as Record<string, unknown>)\n : undefined;\n state = parseState(data) ?? createInitialState();\n lastNativeCompactionId = typeof data?.nativeLastCompactionId === 'string' ? data.nativeLastCompactionId : undefined;\n const validMessages = (value: unknown): value is AutocompactMessage[] =>\n Array.isArray(value) &&\n value.every((message) => message && typeof message === 'object' && typeof message.role === 'string');\n snapshot = validMessages(data?.nativeSnapshot) ? data.nativeSnapshot : undefined;\n previousSnapshot = validMessages(data?.nativePreviousSnapshot) ? data.nativePreviousSnapshot : undefined;\n // A marker can commit before its following state entry. Recover only the exact\n // request after the saved state, rather than retrying against already-compacted evidence.\n if (entry?.id && state.phase === 'checkpoint_ready' && state.requestId) {\n const artifacts = await matching(\n execution,\n (item) =>\n (item.type === 'custom' && item.customType === CHECKPOINT_MESSAGE_TYPE) ||\n customMessage(item)?.customType === CONTEXT_MESSAGE_TYPE,\n entry?.id,\n );\n const committed = artifacts.findLast((item) => {\n const message = item.type === 'message' ? item.message : undefined;\n if (message?.role !== 'custom' || message.customType !== CONTEXT_MESSAGE_TYPE) return false;\n const details = contextDetailsFromUnknown(message.details);\n return (\n details !== undefined &&\n details.poAutocompact.requestId === state.requestId &&\n details.poAutocompact.cycle === state.cycle &&\n details.poAutocompact.pass === state.pass &&\n details.poAutocompact.snapshotLeafId === state.snapshotLeafId &&\n isStructuredCheckpoint(checkpointSummaryFromEntry(item) ?? '')\n );\n });\n if (committed?.type === 'message' && committed.message.role === 'custom') {\n const details = contextDetailsFromUnknown(committed.message.details)!;\n state.readFiles = details.readFiles;\n state.modifiedFiles = details.modifiedFiles;\n resetCycle();\n await persist(execution, version);\n } else {\n const staged = artifacts.findLast((item) => {\n if (item.type !== 'custom' || item.customType !== CHECKPOINT_MESSAGE_TYPE) return false;\n const details = item.data as Record<string, unknown> | undefined;\n return (\n details?.version === STATE_VERSION &&\n details.requestId === state.requestId &&\n details.cycle === state.cycle &&\n details.pass === state.pass &&\n isStructuredCheckpoint(checkpointSummaryFromEntry(item) ?? '')\n );\n });\n if (staged && (state.pass === 1 || state.pass === 2)) {\n previousSnapshot = snapshot;\n state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;\n state.checkpointQueue = state.checkpointQueue.filter((pass) => pass !== state.pass);\n state.pass = state.pass === 1 ? 2 : 3;\n state.phase = 'waiting';\n state.invalidAttempts = 0;\n clear();\n await persist(execution, version);\n }\n }\n }\n if (state.phase !== 'waiting' && (state.phase !== 'checkpoint_ready' || !snapshot)) {\n // ponytail: snapshot-free pending work regenerates after restart; durable prefix reconstruction can avoid this cost later.\n state.phase = 'waiting';\n clear();\n delete state.lastAttemptLeafId;\n await persist(execution, version);\n }\n if (!alive(version)) return;\n const progressed = enqueue(() => progress(execution));\n scheduleMirror(execution);\n await progressed;\n };\n const restore = async (execution: PoHeadlessExecutionContext) => {\n const version = generation + 1;\n try {\n await load(execution);\n } catch (error) {\n await fail(execution, version, error);\n }\n };\n const hooks: PoHeadlessHook[] = [\n { event: 'session_start', handle: (_event, execution) => restore(execution) },\n {\n event: 'session_tree',\n handle: (event, execution) => {\n if (!active) return;\n if (event.status === 'started') {\n navigating = true;\n generation += 1;\n controller?.abort(new Error('Autocompact navigation started.'));\n return;\n }\n return restore(execution);\n },\n },\n {\n event: 'turn_end',\n handle: (_event, execution) => enqueue(() => progress(execution)),\n },\n { event: 'agent_settled', handle: (_event, execution) => enqueue(() => progress(execution)) },\n {\n event: 'session_before_compact',\n handle: (event, execution) => {\n if (!active || navigating) return;\n if (event.reason === 'manual') return manualCompaction(event, execution);\n return !degraded &&\n configured(execution).enabled &&\n event.reason === 'threshold' &&\n (state.phase === 'checkpoint_pending' || state.phase === 'checkpoint_ready')\n ? { cancel: true }\n : undefined;\n },\n },\n {\n event: 'context',\n async handle(event, execution) {\n if (!active || navigating || !Array.isArray(event.messages)) return;\n const started = Date.now();\n try {\n const version = generation;\n const entries = await contextBranch(execution);\n if (!alive(version)) return;\n const projection = projectContextMessages(event.messages as AutocompactMessage[], entries);\n if (projection.invalidMarker) {\n const id = leaf(entries);\n if (!invalid.has(id)) {\n invalid.add(id);\n await telemetry.recordError(\n AUTOCOMPACT_EVENT.contextMarkerInvalid,\n new Error('Po autocompact context marker is malformed.'),\n { ...attributes(), 'autocompact.leaf_id': id },\n );\n }\n return;\n }\n if (!projection.marker) return;\n if (!applied.has(projection.marker.requestId)) {\n applied.add(projection.marker.requestId);\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextApplied, {\n ...attributes(),\n 'autocompact.request.id': projection.marker.requestId,\n 'autocompact.cycle': projection.marker.cycle,\n 'autocompact.pass': projection.marker.pass,\n 'autocompact.snapshot_leaf_id': projection.marker.snapshotLeafId,\n 'autocompact.tokens_before': projection.marker.tokensBefore,\n 'autocompact.message_count.before': event.messages.length,\n 'autocompact.message_count.after': projection.messages.length,\n 'autocompact.message_count.retained': projection.retainedMessageCount,\n });\n }\n return alive(version) ? { messages: projection.messages } : undefined;\n } finally {\n const hookMs = Date.now() - started;\n if (active && hookMs >= SLOW_CONTEXT_HOOK_MS)\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextHookSlow, {\n ...attributes(),\n hook_ms: hookMs,\n 'autocompact.message_count': event.messages.length,\n });\n }\n },\n },\n {\n event: 'session_compact',\n handle: (event, execution) => {\n if (\n !active ||\n event.status !== 'completed' ||\n typeof event.entryId !== 'string' ||\n event.entryId === lastNativeCompactionId\n )\n return;\n const observedGeneration = generation;\n return enqueue(async () => {\n const entries = (await execution.session.entries({\n type: 'compaction',\n limit: 1,\n })) as unknown as CompactionPolicyEntry[];\n const compacted = entries[0];\n if (\n !alive(observedGeneration) ||\n !compacted ||\n compacted.type !== 'compaction' ||\n compacted.id !== event.entryId ||\n compacted.id === lastNativeCompactionId\n )\n return;\n generation += 1;\n const version = generation;\n controller?.abort(new Error('Native compaction superseded checkpoint.'));\n controller = undefined;\n lastNativeCompactionId = compacted.id;\n const files = mergeFileDetails(\n state,\n undefined,\n fileDetailsFromUnknown('details' in compacted ? compacted.details : undefined),\n );\n state.readFiles = files.readFiles;\n state.modifiedFiles = files.modifiedFiles;\n await execution.session.setLabel?.(compacted.id, `autocompact:c${state.cycle}:external`);\n if (!alive(version)) return;\n const plan = (await execution.session.entries({\n type: 'custom',\n customType: PLAN_DOCUMENT_ENTRY,\n limit: 1,\n })) as unknown as CompactionPolicyEntry[];\n const runtimeAttributes = await runtimeState(execution, plan, version);\n if (!alive(version)) return;\n const nativeAttributes = attributes();\n resetCycle();\n await persist(execution, version);\n scheduleMirror(execution);\n if (alive(version))\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.nativeCompactionCompleted, {\n ...nativeAttributes,\n 'autocompact.native.reason': typeof event.reason === 'string' ? event.reason : 'unknown',\n 'autocompact.native.from_extension': 'fromHook' in compacted && compacted.fromHook === true,\n 'autocompact.tokens_before': compacted.tokensBefore,\n ...runtimeAttributes,\n });\n });\n },\n },\n ];\n return {\n hooks,\n plugin(cordis) {\n cordis.inject([PO_UI_HUB_SERVICE], (injected) => {\n const contribution = requirePoUiHub(injected).registerFooter({\n source: FOOTER_SOURCE,\n id: 'autocompact',\n order: FOOTER_ORDER,\n });\n footer = contribution;\n if (context && active) refreshStatus(context);\n return () => {\n contribution.dispose();\n if (footer === contribution) footer = undefined;\n };\n });\n cordis.inject([PO_CONTEXT_CONTRIBUTIONS_SERVICE], (injected) => {\n const service = requirePoContextContributions(injected);\n contributions = service;\n return () => {\n if (contributions === service) contributions = undefined;\n };\n });\n },\n start: restore,\n async stop() {\n active = false;\n checkpointBoundary?.dispose();\n checkpointBoundary = undefined;\n generation += 1;\n controller?.abort(new Error('Autocompact is shutting down.'));\n await Promise.allSettled([...work, serial]);\n context?.client.setStatus(STATUS_KEY, undefined);\n footer?.update(undefined);\n footer = undefined;\n context = undefined;\n contributions = undefined;\n await telemetry.shutdown();\n },\n };\n}\n","import { defineRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createAutocompactTelemetry } from '../../../../services/autocompactTelemetry';\nimport { createNativeAutocompact } from '../../../../services/nativeAutocompact';\n\nexport default defineRoot(({ agent }: PoServerPluginContext) => {\n const runtime = createNativeAutocompact({\n telemetry: createAutocompactTelemetry({ env: agent?.context.environment, cwd: agent?.context.cwd }),\n });\n return { value: runtime, services: [runtime.plugin], onDispose: runtime.stop };\n});\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'agent_settled')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'context')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_before_compact')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_compact')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_start')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_tree')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'turn_end')!,\n);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport hookAgentSettled from '../src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server';\nimport hookContext from '../src/extensions/workspaces/sessions/(backend)/hook/context.server';\nimport hookSessionBeforeCompact from '../src/extensions/workspaces/sessions/(backend)/hook/session-before-compact.server';\nimport hookSessionCompact from '../src/extensions/workspaces/sessions/(backend)/hook/session-compact.server';\nimport hookSessionStart from '../src/extensions/workspaces/sessions/(backend)/hook/session-start.server';\nimport hookSessionTree from '../src/extensions/workspaces/sessions/(backend)/hook/session-tree.server';\nimport hookTurnEnd from '../src/extensions/workspaces/sessions/(backend)/hook/turn-end.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-autocompact',\n providerOverrides: composeServerProviderOverrides(rootSession),\n injects: composeRootInjects({ session: [rootSession] }),\n session: async (context) => {\n const scopeSession = await context.scopeRoot('session', rootSession, context);\n const contextSession = { ...context, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeSession),\n get hooks(): PoServerSessionPlugin['hooks'] { return [via({ event: 'agent_settled' }, at(hookAgentSettled, contextSession)), via({ event: 'context' }, at(hookContext, contextSession)), via({ event: 'session_before_compact' }, at(hookSessionBeforeCompact, contextSession)), via({ event: 'session_compact' }, at(hookSessionCompact, contextSession)), via({ event: 'session_start' }, at(hookSessionStart, contextSession)), via({ event: 'session_tree' }, at(hookSessionTree, contextSession)), via({ event: 'turn_end' }, at(hookTurnEnd, contextSession))]; },\n services: [...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;;;AAOA,MAAM,eAAe;AACrB,MAAM,eAAe;AAErB,MAAa,oBAAoB;CAC/B,mBAAmB;CACnB,qBAAqB;CACrB,kBAAkB;CAClB,mBAAmB;CACnB,yBAAyB;CACzB,6BAA6B;CAC7B,kBAAkB;CAClB,gBAAgB;CAChB,sBAAsB;CACtB,iBAAiB;CACjB,2BAA2B;CAC3B,oBAAoB;AACtB;AA2BA,SAAgB,2BAA2B,UAAuC,CAAC,GAAyB;CAC1G,MAAM,YAAyB,kBAAkB;EAC/C,aAAa;EACb,aAAa;EACb,KAAK,QAAQ;EACb,eAAe,QAAQ;EACvB,KAAK,QAAQ;EACb,kBAAkB,QAAQ;EAC1B,MAAM,QAAQ;EACd,YAAY;EACZ,cAAc;CAChB,CAAC;CACD,OAAO;EACL,cAAc,OAAO,OAAO,YAAY,iBACtC,UAAU,YAAY,OAAO,OAAO,YAAY,YAAY;EAC9D,gBAAgB,OAAO,OAAO,eAAe,UAAU,cAAc,OAAO,OAAO,UAAU;EAC7F,cAAc,OAAO,eAAe,UAAU,YAAY,OAAO,UAAU;EAC3E,YAAY,MAAM,YAAY,aAAa,UAAU,UAAU,MAAM,YAAY,QAAQ;EACzF,aAAa,UAAU,MAAM;EAC7B,gBAAgB,UAAU,SAAS;CACrC;AACF;;;ACtEA,MAAa,sBAAsB;AACnC,MAAa,gBAAgB;AAE7B,MAAa,aAAa;;;AC2B1B,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,SAAgB,mBAAmB,QAAoE;CACrG,KAAK,MAAM,SAAS,OAAO,WAAW,GAAG;EACvC,IAAI,MAAM,SAAS,YAAY,MAAM,eA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AAS,mBAAmB,EAAE,SAAS,CAACA,mBAAW,EAAE,CAAC;CACtD,SAAS,OAAO,YAAY;EAC1B,MAAM,eAAe,MAAM,QAAQ,UAAU,WAAWA,qBAAa,OAAO;EAC5E,MAAM,iBAAiB;GAAE,GAAG;GAAS,MAAM,aAAa;EAAM;EAC9D,OAAO;GACL,GAAG,iBAAiB,YAAY;GAChC,IAAI,QAAwC;IAAE,OAAO;KAAC,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,8BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,UAAU,GAAG,GAAGC,wBAAa,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,yBAAyB,GAAG,GAAGC,uCAA0B,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,kBAAkB,GAAG,GAAGC,gCAAoB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,8BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,eAAe,GAAG,GAAGC,6BAAiB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,WAAW,GAAG,GAAGC,yBAAa,cAAc,CAAC;IAAC;GAAG;GACtiB,UAAU,CAAC,GAAI,aAAa,YAAY,CAAC,CAAE;GAC3C,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EACvG;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"server.mjs","names":["rootSession","hookAgentSettled","hookContext","hookSessionBeforeCompact","hookSessionCompact","hookSessionStart","hookSessionTree","hookTurnEnd"],"sources":["../../src/services/admittedModes/index.ts","../../src/services/autocompactTelemetry/index.ts","../../src/constants/runtime.ts","../../src/services/autocompactRuntime/index.ts","../../src/services/compactionHistory/index.ts","../../src/services/modelOverrides/index.ts","../../src/services/summarizationModel/index.ts","../../src/services/nativeAutocompact/index.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/context.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-before-compact.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-compact.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-start.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/session-tree.server.ts","../../src/extensions/workspaces/sessions/(backend)/hook/turn-end.server.ts","../../generated/server.ts"],"sourcesContent":["import type { Context } from '@deepseek-ai/cordis';\n\nimport type { AdmittedModes } from './type';\n\n/**\n * Node reads the Po config files itself, afresh on every hook, so it admits nothing here.\n * The edge build replaces this module with `index.edge.ts`, which reads the host-admitted snapshot.\n */\nexport function admittedModes(_context: Context): AdmittedModes | undefined {\n return undefined;\n}\n","import {\n createPoTelemetry,\n type PoTelemetry,\n type PoTelemetryErrorOptions,\n type PoTelemetryOptions,\n} from '@agimon-ai/po-core/telemetry';\n\nconst SERVICE_NAME = 'po-autocompact';\nconst PACKAGE_NAME = '@agimon-ai/po-autocompact';\n\nexport const AUTOCOMPACT_EVENT = {\n checkpointStarted: 'po_autocompact.checkpoint_started',\n checkpointCompleted: 'po_autocompact.checkpoint_completed',\n checkpointFailed: 'po_autocompact.checkpoint_failed',\n checkpointInvalid: 'po_autocompact.checkpoint_invalid',\n configurationLoadFailed: 'po_autocompact.configuration_load_failed',\n contextContributionDegraded: 'po_autocompact.context_contribution_degraded',\n contextCommitted: 'po_autocompact.context_committed',\n contextApplied: 'po_autocompact.context_applied',\n contextMarkerInvalid: 'po_autocompact.context_marker_invalid',\n contextHookSlow: 'po_autocompact.context_hook_slow',\n nativeCompactionCompleted: 'po_autocompact.native_compaction_completed',\n historyWriteFailed: 'po_autocompact.history_write_failed',\n} as const;\n\nexport type AutocompactEventName = (typeof AUTOCOMPACT_EVENT)[keyof typeof AUTOCOMPACT_EVENT];\nexport type AutocompactEventAttributes = Record<string, string | number | boolean>;\n\nexport interface AutocompactTelemetryOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<PoTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n}\n\nexport interface AutocompactTelemetry {\n recordError(\n event: AutocompactEventName,\n error: unknown,\n attributes?: AutocompactEventAttributes,\n options?: PoTelemetryErrorOptions,\n ): Promise<void>;\n recordWarning(event: AutocompactEventName, error: unknown, attributes?: AutocompactEventAttributes): Promise<void>;\n recordEvent(event: AutocompactEventName, attributes?: AutocompactEventAttributes): Promise<void>;\n runInSpan<T>(name: string, attributes: AutocompactEventAttributes, callback: () => Promise<T>): Promise<T>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createAutocompactTelemetry(options: AutocompactTelemetryOptions = {}): AutocompactTelemetry {\n const telemetry: PoTelemetry = createPoTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n });\n return {\n recordError: (event, error, attributes, errorOptions) =>\n telemetry.recordError(event, error, attributes, errorOptions),\n recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),\n recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),\n runInSpan: (name, attributes, callback) => telemetry.runInSpan(name, attributes, callback),\n flush: () => telemetry.flush(),\n shutdown: () => telemetry.shutdown(),\n };\n}\n","export const ROOT_WORKING_LEAF = '@root';\nexport const PLAN_DOCUMENT_ENTRY = 'agent-harness-plan-document';\nexport const FOOTER_SOURCE = 'po-autocompact';\nexport const FOOTER_ORDER = 20;\nexport const STATUS_KEY = 'po-autocompact';\nexport const STATE_PHASE = {\n waiting: 'waiting',\n checkpointPending: 'checkpoint_pending',\n checkpointReady: 'checkpoint_ready',\n compacting: 'compacting',\n} as const;\n\n/**\n * Above this, the context hook is worth a telemetry event. Below it the hook is\n * noise against a round trip measured in seconds, and it runs on every request.\n */\nexport const SLOW_CONTEXT_HOOK_MS = 25;\n","import { loadPoConfig, type AutocompactOverrideConfig, type PlanningAgentConfig } from '@agimon-ai/po-config';\nimport {\n PO_CONTEXT_CONTRIBUTIONS_SERVICE,\n type PoContextContributionEntry,\n type PoContextContributionError,\n type PoContextContributionsService,\n type PoContextContributionsSnapshot,\n} from '@agimon-ai/po-core/contextContributions';\n\nimport { PLAN_DOCUMENT_ENTRY } from '../../constants/runtime';\nimport type { AutocompactPass, AutocompactRatioOverrides } from '../../types/autocompact';\nimport type { AdmittedModes, AutocompactModes } from '../admittedModes/type';\nimport type { CompactionPolicyEntry } from '../compactionPolicy';\n\ninterface PlanSnapshot {\n content: string;\n path: string;\n}\n\ninterface SteeringSnapshot {\n plan?: PlanSnapshot;\n contextContributions: PoContextContributionsSnapshot;\n readFiles: string[];\n modifiedFiles: string[];\n}\n\ninterface RuntimeStateSnapshot {\n planPath?: string;\n contributions: readonly PoContextContributionEntry[];\n contributionErrors: readonly PoContextContributionError[];\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function latestPlanSnapshot(branch: readonly CompactionPolicyEntry[]): PlanSnapshot | undefined {\n for (const entry of branch.toReversed()) {\n if (entry.type !== 'custom' || entry.customType !== PLAN_DOCUMENT_ENTRY) continue;\n if (!entry.data || typeof entry.data !== 'object') return undefined;\n const data = entry.data as Record<string, unknown>;\n if (typeof data.content !== 'string' || typeof data.path !== 'string') return undefined;\n return { content: data.content, path: data.path };\n }\n return undefined;\n}\n\nconst EMPTY_CONTEXT_CONTRIBUTIONS: PoContextContributionsSnapshot = Object.freeze({\n entries: Object.freeze([]),\n errors: Object.freeze([]),\n});\n\nexport function readContextContributionsSnapshot(\n service: PoContextContributionsService | undefined,\n): PoContextContributionsSnapshot {\n if (!service) return EMPTY_CONTEXT_CONTRIBUTIONS;\n try {\n return service.snapshot();\n } catch (error) {\n return {\n entries: [],\n errors: [\n {\n source: PO_CONTEXT_CONTRIBUTIONS_SERVICE,\n id: 'service-snapshot',\n label: 'Context contributions',\n order: 0,\n message: errorMessage(error),\n },\n ],\n };\n }\n}\n\nfunction formatContextContributions(snapshot: PoContextContributionsSnapshot): string {\n const sections = snapshot.entries.map((entry) => `### ${entry.label}\\n${entry.text}`);\n sections.push(...snapshot.errors.map((error) => `### ${error.label}\\n(unavailable: ${error.message})`));\n return sections.length > 0 ? sections.join('\\n\\n') : '(no registered context contributions)';\n}\n\nexport function runtimeStateSnapshot(\n branch: readonly CompactionPolicyEntry[],\n contextContributions: PoContextContributionsSnapshot,\n): RuntimeStateSnapshot {\n const plan = latestPlanSnapshot(branch);\n return {\n ...(plan ? { planPath: plan.path } : {}),\n contributions: contextContributions.entries,\n contributionErrors: contextContributions.errors,\n };\n}\n\nexport function formatRuntimeState(snapshot: RuntimeStateSnapshot): string {\n const plan = snapshot.planPath\n ? `Source: ${snapshot.planPath}\\nExact plan content is restored separately by Po Plan.`\n : '(no active plan document)';\n return `<compaction-runtime-state>\nAuthoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.\n<active-plan>\n${plan}\n</active-plan>\n<context-contributions>\n${formatContextContributions({ entries: snapshot.contributions, errors: snapshot.contributionErrors })}\n</context-contributions>\n</compaction-runtime-state>`;\n}\n\nfunction steeringEnvelope(snapshot: SteeringSnapshot): string {\n const plan = snapshot.plan\n ? `Source: ${snapshot.plan.path}\\n\\n${snapshot.plan.content}`\n : '(no active plan document)';\n const importantContext = [\n snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(', ')}` : undefined,\n snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(', ')}` : undefined,\n ].filter((value): value is string => Boolean(value));\n\n return `<compaction-steering priority=\"user,plan,context-contributions,important-context,recent-messages\">\n<user-prompt source=\"conversation\">\nTreat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.\n</user-prompt>\n<active-plan>\n${plan}\n</active-plan>\n<context-contributions>\n${formatContextContributions(snapshot.contextContributions)}\n</context-contributions>\n<important-context>\n${importantContext.length > 0 ? importantContext.join('\\n') : '(none recorded outside the conversation)'}\n</important-context>\n</compaction-steering>`;\n}\n\nexport function checkpointInstructions(pass: AutocompactPass, steering: SteeringSnapshot): string {\n const decision =\n pass === 2\n ? 'Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.\\n\\n'\n : '';\n\n // Summarization is a tool-less single LLM call, so instructions describe only what to\n // produce. Directives aimed at an implementing agent leak into the checkpoint body.\n return `Create Po autocompact checkpoint pass ${pass}.\n\n${steeringEnvelope(steering)}\n\nApply the steering evidence in priority order. Do not invent plan or contributed runtime state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.\n\n${decision}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.\n\n## Goal\n## Constraints & Preferences\n## Progress\n### Done\n### In Progress\n### Blocked\n## Key Decisions\n## Next Steps\n## Critical Context`;\n}\n\ninterface AutocompactRuntimeConfig {\n /** Off leaves compaction to the host; unset is on. */\n enabled: boolean;\n /** The agent that writes the summaries, from autocompact's own keys or planning's. */\n agent?: PlanningAgentConfig;\n ratios: AutocompactRatioOverrides;\n /** Per-model absolute token checkpoints, tried in file order. */\n overrides: readonly AutocompactOverrideConfig[];\n}\n\nconst DEFAULT_RUNTIME_CONFIG: AutocompactRuntimeConfig = { enabled: true, ratios: {}, overrides: [] };\n\n/** While admitted settings cannot be read a disable could be hidden, so autocompact stands down for the host. */\nconst UNAVAILABLE_RUNTIME_CONFIG: AutocompactRuntimeConfig = { enabled: false, ratios: {}, overrides: [] };\n\n/**\n * What the Po config says about this package.\n *\n * `modes.autocompact` is read first and `modes.planning.subagents` is the\n * fallback, because summarization borrowed the planning subagent model before\n * it had keys of its own and existing files still spell it that way.\n *\n * A host that admits its configuration passes `admitted`, and that is read instead of the files. Reading it\n * failing is reported and stands autocompact down, where unreadable files keep the session model and stay on.\n */\nexport function autocompactRuntimeConfig(\n root: string,\n onLoadFailure?: (error: unknown) => void,\n admitted?: AdmittedModes,\n): AutocompactRuntimeConfig {\n let modes: AutocompactModes | undefined;\n try {\n modes = admitted ? admitted() : loadPoConfig(root).modes;\n } catch (error) {\n if (admitted) {\n onLoadFailure?.(error);\n return UNAVAILABLE_RUNTIME_CONFIG;\n }\n process.emitWarning('Po autocompact configuration could not be loaded; using the active session model instead.');\n onLoadFailure?.(error);\n return DEFAULT_RUNTIME_CONFIG;\n }\n const configured = modes?.autocompact;\n const ownAgent: PlanningAgentConfig | undefined =\n configured && (configured.model !== undefined || configured.thinking !== undefined)\n ? {\n ...(configured.model ? { model: configured.model } : {}),\n ...(configured.thinking ? { thinking: configured.thinking } : {}),\n }\n : undefined;\n const agent = ownAgent ?? modes?.planning?.subagents;\n const thresholds = configured?.thresholds;\n return {\n enabled: configured?.enabled ?? true,\n ...(agent ? { agent } : {}),\n ratios: {\n ...(thresholds?.pass1 === undefined ? {} : { 1: thresholds.pass1 }),\n ...(thresholds?.pass2 === undefined ? {} : { 2: thresholds.pass2 }),\n ...(thresholds?.pass3 === undefined ? {} : { 3: thresholds.pass3 }),\n },\n overrides: configured?.overrides ?? [],\n };\n}\n","import {\n ArtifactAccessError,\n COMPACTION_ARTIFACT_DIRECTORY,\n listArtifacts,\n openArtifact,\n readArtifactBytes,\n removeArtifact,\n writeArtifactText,\n} from '@agimon-ai/po-artifact/artifactFiles';\n\nimport { CHECKPOINT_MESSAGE_TYPE, CONTEXT_MESSAGE_TYPE } from '../../constants/autocompact';\nimport {\n checkpointSummaryFromEntry,\n contextDetailsFromUnknown,\n customMessage,\n type CompactionPolicyEntry,\n} from '../compactionPolicy';\nimport type { CompactionHistoryFile } from './type';\n\nconst FORMAT = 'po-compaction/1';\nconst HEADER = `---\\nformat: ${JSON.stringify(FORMAT)}\\n`;\nconst HISTORY_PATH = new RegExp(\n `^${COMPACTION_ARTIFACT_DIRECTORY}/(?:epoch-\\\\d+/(?:summary|checkpoint-\\\\d+)|in-epoch/checkpoint-\\\\d+)\\\\.md$`,\n);\n// Native compaction wraps its summary this way (pi-durable dist/harness/compaction.js, po-core piMessages).\nconst NATIVE_PREFIX =\n 'The conversation history before this point was compacted into the following summary:\\n\\n<summary>\\n';\nconst NATIVE_SUFFIX = '\\n</summary>';\n\ntype HistoryFields = Record<string, string | number | undefined>;\n\nfunction historyFile(path: string, fields: HistoryFields, body: string): CompactionHistoryFile {\n const header = Object.entries({ format: FORMAT, ...fields }).flatMap(([key, value]) =>\n value === undefined ? [] : [`${key}: ${JSON.stringify(value)}`],\n );\n return { path: `${COMPACTION_ARTIFACT_DIRECTORY}/${path}`, text: `---\\n${header.join('\\n')}\\n---\\n\\n${body}\\n` };\n}\n\nfunction isoTime(value: string | number): string | undefined {\n const time = new Date(value);\n return Number.isFinite(time.getTime()) ? time.toISOString() : undefined;\n}\n\nfunction passOf(value: unknown): number | undefined {\n if (typeof value !== 'object' || value === null || !('pass' in value)) return undefined;\n return value.pass === 1 || value.pass === 2 || value.pass === 3 ? value.pass : undefined;\n}\n\nfunction committedFields(entry: CompactionPolicyEntry): { body: string; fields: HistoryFields } | undefined {\n if (entry.type === 'compaction') {\n const summary = entry.summary.trim();\n const body =\n summary.startsWith(NATIVE_PREFIX) && summary.endsWith(NATIVE_SUFFIX)\n ? summary.slice(NATIVE_PREFIX.length, -NATIVE_SUFFIX.length).trim()\n : summary;\n return {\n body,\n fields: { source: 'compact', tokensBefore: entry.tokensBefore > 0 ? entry.tokensBefore : undefined },\n };\n }\n const marker = customMessage(entry);\n const details = marker?.customType === CONTEXT_MESSAGE_TYPE ? contextDetailsFromUnknown(marker.details) : undefined;\n if (!details) return undefined;\n return {\n body: checkpointSummaryFromEntry(entry) ?? '',\n fields: {\n source: 'autocompact',\n pass: details.poAutocompact.pass,\n tokensBefore: details.poAutocompact.tokensBefore,\n },\n };\n}\n\n/** The only entries `wantedHistory` reads, so mirrors can scan history without keeping the rest. */\nexport function isHistoryEntry(entry: CompactionPolicyEntry): boolean {\n const type = customMessage(entry)?.customType;\n return (\n entry.type === 'compaction' ||\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n type === CHECKPOINT_MESSAGE_TYPE ||\n type === CONTEXT_MESSAGE_TYPE\n );\n}\n\n/** Number commits along the active branch so a rewind rewrites the same epoch folders. */\nexport function wantedHistory(entries: readonly CompactionPolicyEntry[]): CompactionHistoryFile[] {\n const files: CompactionHistoryFile[] = [];\n let staged: Array<{ entry: CompactionPolicyEntry; summary: string; pass: number | undefined }> = [];\n let epoch = 1;\n const checkpoints = (folder: string) =>\n staged.map(({ entry, summary, pass }, index) =>\n historyFile(\n `${folder}/checkpoint-${index + 1}.md`,\n {\n kind: 'checkpoint',\n epoch,\n checkpoint: index + 1,\n entryId: entry.id,\n source: 'autocompact',\n pass,\n timestamp: isoTime(entry.timestamp),\n },\n summary,\n ),\n );\n for (const entry of entries) {\n const marker = customMessage(entry);\n if (\n (entry.type === 'custom' && entry.customType === CHECKPOINT_MESSAGE_TYPE) ||\n marker?.customType === CHECKPOINT_MESSAGE_TYPE\n ) {\n const summary = checkpointSummaryFromEntry(entry);\n if (summary)\n staged.push({ entry, summary, pass: passOf(entry.type === 'custom' ? entry.data : marker?.details) });\n continue;\n }\n const committed = committedFields(entry);\n if (!committed) continue;\n files.push(\n ...checkpoints(`epoch-${epoch}`),\n historyFile(\n `epoch-${epoch}/summary.md`,\n { kind: 'summary', epoch, entryId: entry.id, ...committed.fields, timestamp: isoTime(entry.timestamp) },\n committed.body,\n ),\n );\n staged = [];\n epoch += 1;\n }\n files.push(...checkpoints('in-epoch'));\n return files;\n}\n\nasync function ownedHistory(root: string, path: string): Promise<boolean> {\n const file = await openArtifact(root, path).catch((error: unknown) => {\n // Gone since the listing: nothing left to prune.\n if (error instanceof ArtifactAccessError && error.status === 404) return undefined;\n throw error;\n });\n if (!file) return false;\n try {\n const bytes = await readArtifactBytes(file.handle, Math.min(file.stat.size, HEADER.length));\n return new TextDecoder().decode(bytes) === HEADER;\n } finally {\n await file.handle.close();\n }\n}\n\n/** Mirror history into the session artifact folder. Pruning touches only files carrying this mirror's header. */\nexport async function mirrorCompactionHistory(root: string, entries: readonly CompactionPolicyEntry[]): Promise<void> {\n const files = wantedHistory(entries);\n // ponytail: rewinding to before the first checkpoint keeps the old files; prune on empty if that ever misleads.\n if (files.length === 0) return;\n for (const file of files) await writeArtifactText(root, file.path, file.text);\n const listed = await listArtifacts(root);\n if (listed.error) throw new Error(listed.error);\n const wanted = new Set(files.map((file) => file.path));\n const stale = listed.items.filter((item) => HISTORY_PATH.test(item.path) && !wanted.has(item.path));\n for (const item of stale) if (await ownedHistory(root, item.path)) await removeArtifact(root, item.path);\n for (const folder of new Set(stale.map((item) => item.path.slice(0, item.path.lastIndexOf('/')))))\n await removeArtifact(root, folder);\n}\n","/**\n * Picks the absolute token checkpoints configured for the model a session is running.\n *\n * DESIGN PATTERNS:\n * - Pure decision function, so the matching rule is unit-testable without a session,\n * a config file or a filesystem\n * - First match in file order wins, so a reader resolves a model by reading down the\n * list rather than by working out which pattern is the most specific\n * - A model matching nothing returns no overrides at all, which leaves the ratio\n * ladder exactly as it behaves without this feature\n *\n * AVOID:\n * - Stripping a thinking suffix the way subagent model scope does. That matches\n * free-typed config strings; this matches a resolved `Model`, whose `id` carries\n * the level in a separate field and never in the id itself.\n * - Matching a bare pattern against `provider/id`. The glob wildcard does not cross\n * the separator, so the subject has to follow the pattern's own shape.\n */\n\nimport type { AutocompactOverrideConfig } from '@agimon-ai/po-config';\nimport { minimatch } from 'minimatch';\n\nimport type { AutocompactTokenOverrides } from '../../types/autocompact';\n\n/** The parts of a resolved model the rules match on. */\nexport interface AutocompactModelIdentity {\n id: string;\n provider: string;\n}\n\n/**\n * A pattern naming a provider is matched against `provider/id`, anything else\n * against the bare id. `*` does not cross `/`, so a bare pattern tested against a\n * qualified subject would never match and would read as a silently dead rule.\n */\nfunction matchesModelPattern(pattern: string, model: AutocompactModelIdentity): boolean {\n const subject = pattern.includes('/') ? `${model.provider}/${model.id}` : model.id;\n return minimatch(subject, pattern, { nocase: true });\n}\n\nexport function resolveModelTokenOverrides(\n model: AutocompactModelIdentity | undefined,\n overrides: readonly AutocompactOverrideConfig[],\n): AutocompactTokenOverrides {\n if (!model) return {};\n const matched = overrides.find((entry) => matchesModelPattern(entry.model, model));\n if (!matched) return {};\n const { pass1, pass2, pass3 } = matched.tokens;\n return {\n ...(pass1 === undefined ? {} : { 1: pass1 }),\n ...(pass2 === undefined ? {} : { 2: pass2 }),\n ...(pass3 === undefined ? {} : { 3: pass3 }),\n };\n}\n","import type { ExtensionContext } from '@earendil-works/pi-coding-agent';\n\nconst THINKING_SUFFIX_PATTERN = /:(off|minimal|low|medium|high|xhigh|max)$/;\n\nexport interface SummarizationModel {\n model: NonNullable<ExtensionContext['model']>;\n thinkingLevel?: NonNullable<ExtensionContext['thinkingLevel']>;\n}\n\nexport interface ModelReference {\n provider: string;\n modelId: string;\n thinking?: NonNullable<ExtensionContext['thinkingLevel']>;\n}\n\n/** Splits a `provider/model` reference, tolerating the optional thinking suffix. */\nexport function parseModelReference(reference: string): ModelReference | undefined {\n const trimmed = reference.trim();\n const thinking = THINKING_SUFFIX_PATTERN.exec(trimmed)?.[1] as SummarizationModel['thinkingLevel'];\n const identity = trimmed.replace(THINKING_SUFFIX_PATTERN, '');\n const separator = identity.indexOf('/');\n if (separator <= 0 || separator >= identity.length - 1) return undefined;\n return {\n provider: identity.slice(0, separator),\n modelId: identity.slice(separator + 1),\n ...(thinking ? { thinking } : {}),\n };\n}\n","import { artifactRoot } from '@agimon-ai/po-artifact/artifactFiles';\nimport {\n PO_CONTEXT_CONTRIBUTIONS_SERVICE,\n requirePoContextContributions,\n type PoContextContributionsService,\n} from '@agimon-ai/po-core/contextContributions';\nimport type { PoFooterContributionHandle } from '@agimon-ai/po-core/footer';\nimport type { PoHeadlessExecutionContext, PoHeadlessHook } from '@agimon-ai/po-core/headless';\nimport { PO_UI_HUB_SERVICE, requirePoUiHub } from '@agimon-ai/po-core/uiHub';\n\nimport {\n CHECKPOINT_MESSAGE_TYPE,\n CONTEXT_MESSAGE_TYPE,\n MAX_INVALID_CHECKPOINT_ATTEMPTS,\n RESUME_MESSAGE_TYPE,\n RUNTIME_STATE_MESSAGE_TYPE,\n STATE_CUSTOM_TYPE,\n STATE_VERSION,\n} from '../../constants/autocompact';\nimport {\n FOOTER_ORDER,\n FOOTER_SOURCE,\n PLAN_DOCUMENT_ENTRY,\n SLOW_CONTEXT_HOOK_MS,\n STATUS_KEY,\n} from '../../constants/runtime';\nimport type { AutocompactContextDetails, AutocompactMessage, AutocompactState } from '../../types/autocompact';\nimport {\n autocompactRuntimeConfig,\n checkpointInstructions,\n formatRuntimeState,\n latestPlanSnapshot,\n readContextContributionsSnapshot,\n runtimeStateSnapshot,\n} from '../autocompactRuntime';\nimport { AUTOCOMPACT_EVENT, createAutocompactTelemetry } from '../autocompactTelemetry';\nimport { isHistoryEntry, mirrorCompactionHistory } from '../compactionHistory';\nimport {\n baselineUsageIsSettled,\n checkpointRequestDetails,\n checkpointSummaryFromEntry,\n contextDetailsFromUnknown,\n createInitialState,\n createRequestId,\n customMessage,\n effectiveThresholds,\n fileDetailsFromUnknown,\n fileOperationsFromMessages,\n isStructuredCheckpoint,\n latestCheckpointArtifactEntry,\n mergeFileDetails,\n parseCheckpointDecision,\n parseState,\n projectContextMessages,\n withCanonicalFileSections,\n type CompactionPolicyEntry,\n} from '../compactionPolicy';\nimport { resolveModelTokenOverrides } from '../modelOverrides';\nimport { parseModelReference } from '../summarizationModel';\nimport type { NativeAutocompactDependencies, NativeAutocompactRuntime } from './type';\n\n/** Exact canonical-prefix comparison refuses to apply summaries to edited or replaced evidence. */\nfunction tailAfter(\n snapshot: readonly AutocompactMessage[],\n current: readonly AutocompactMessage[],\n): AutocompactMessage[] | undefined {\n if (\n snapshot.length > current.length ||\n snapshot.some((message, index) => JSON.stringify(message) !== JSON.stringify(current[index]))\n )\n return undefined;\n return current.slice(snapshot.length);\n}\n\nfunction leaf(entries: readonly CompactionPolicyEntry[]): string {\n return (\n entries.findLast(\n (entry) =>\n entry.type !== 'custom' ||\n (entry.customType !== STATE_CUSTOM_TYPE && entry.customType !== CHECKPOINT_MESSAGE_TYPE),\n )?.id ?? 'root'\n );\n}\n\nexport function createNativeAutocompact(dependencies: NativeAutocompactDependencies = {}): NativeAutocompactRuntime {\n const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();\n let active = true;\n let generation = 0;\n let state: AutocompactState = createInitialState();\n let snapshot: AutocompactMessage[] | undefined;\n let previousSnapshot: AutocompactMessage[] | undefined;\n let context: PoHeadlessExecutionContext | undefined;\n let contributions: PoContextContributionsService | undefined;\n let controller: AbortController | undefined;\n let serial: Promise<void> = Promise.resolve();\n const work = new Set<Promise<void>>();\n const applied = new Set<string>();\n const invalid = new Set<string>();\n let configFailureReported = false;\n let footer: PoFooterContributionHandle | undefined;\n let navigating = false;\n let degraded = false;\n let lastNativeCompactionId: string | undefined;\n let checkpointBoundary:\n | ReturnType<NonNullable<PoHeadlessExecutionContext['session']['registerCheckpointBoundary']>>\n | undefined;\n let mirrorQueued = false;\n let historyWarnedSession: string | undefined;\n\n const attributes = () => ({\n 'pi.session.id': context?.sessionId ?? '',\n 'autocompact.cycle': state.cycle,\n 'autocompact.pass': state.pass,\n ...(state.requestId ? { 'autocompact.request.id': state.requestId } : {}),\n ...(state.snapshotLeafId ? { 'autocompact.snapshot_leaf_id': state.snapshotLeafId } : {}),\n ...(state.snapshotTokens === undefined ? {} : { 'autocompact.tokens_before': state.snapshotTokens }),\n });\n const configured = (execution: PoHeadlessExecutionContext) =>\n autocompactRuntimeConfig(\n execution.repoRoot,\n (error) => {\n if (!configFailureReported) {\n configFailureReported = true;\n void telemetry.recordWarning(AUTOCOMPACT_EVENT.configurationLoadFailed, error, {\n ...attributes(),\n 'failure.kind': 'configuration',\n });\n // With admitted settings unreadable autocompact stands down, so the person is told rather than left to guess.\n if (dependencies.modes)\n void Promise.allSettled([\n Promise.resolve().then(() =>\n execution.client.notify({\n body: `Po autocompact is paused until its configuration is available: ${error instanceof Error ? error.message : String(error)}`,\n level: 'warning',\n }),\n ),\n ]);\n }\n },\n dependencies.modes,\n );\n const alive = (version: number) => active && !navigating && generation === version;\n const refreshStatus = (execution: PoHeadlessExecutionContext) => {\n const phase =\n state.phase === 'checkpoint_pending'\n ? 'summarizing'\n : state.phase === 'checkpoint_ready'\n ? 'applying'\n : undefined;\n footer?.update(phase ? { fullText: `Compacting p${state.pass}`, compactText: `C${state.pass}` } : undefined);\n execution.client.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : undefined);\n };\n const enqueue = (callback: () => Promise<void>): Promise<void> => {\n const version = generation;\n const operation = serial.then(async () => {\n if (alive(version)) await callback();\n });\n serial = operation.catch(() => undefined);\n return operation;\n };\n const persist = async (execution: PoHeadlessExecutionContext, version: number) => {\n if (!alive(version)) return;\n await execution.session.appendCustomEntry(STATE_CUSTOM_TYPE, {\n ...state,\n nativeLastCompactionId: lastNativeCompactionId,\n });\n if (alive(version)) refreshStatus(execution);\n };\n const clear = () => {\n delete state.requestId;\n delete state.snapshotLeafId;\n delete state.snapshotTokens;\n delete state.pendingCheckpoint;\n delete state.compactionPass;\n snapshot = undefined;\n };\n const fail = async (\n execution: PoHeadlessExecutionContext,\n version: number,\n error: unknown,\n malformed = false,\n kind:\n | 'empty_checkpoint'\n | 'evidence_changed'\n | 'configuration'\n | 'persistence'\n | 'validation'\n | 'unknown' = 'unknown',\n ) => {\n if (!alive(version)) return;\n degraded = true;\n const eventAttributes = attributes();\n const attempts = state.invalidAttempts + 1;\n const pass = state.pass;\n const failedLeaf = state.snapshotLeafId;\n state.invalidAttempts += 1;\n if (state.invalidAttempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS) {\n state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);\n state.exhaustedPasses.push(pass);\n state.invalidAttempts = 0;\n }\n state.phase = 'waiting';\n clear();\n state.lastAttemptLeafId = failedLeaf;\n const errors = [error];\n try {\n await persist(execution, version);\n } catch (persistError) {\n errors.push(persistError);\n }\n if (!alive(version)) return;\n // Reporting is best effort: neither sink may prevent recovery or the native-compaction fallback.\n await Promise.allSettled([\n Promise.resolve().then(() =>\n execution.client.notify({\n body: `Po autocompact summarization pass ${pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n level: 'error',\n }),\n ),\n ...errors.map((failure, index) =>\n Promise.resolve().then(() =>\n telemetry.recordError(\n malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed,\n failure,\n {\n ...eventAttributes,\n 'failure.kind': index === 0 ? kind : 'persistence',\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS,\n },\n // The summarizer's failure is the only clue to why a pass failed; the sink redacts secrets.\n { includeException: true },\n ),\n ),\n ),\n ]);\n };\n // Stream history newest first, keeping only matching entries (oldest first), so large custom journals never pile up.\n const matching = async (\n execution: PoHeadlessExecutionContext,\n keep: (entry: CompactionPolicyEntry) => boolean,\n stopAt?: string,\n ) => {\n const entries: CompactionPolicyEntry[] = [];\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n if (entry.id === stopAt) break;\n if (keep(entry)) entries.push(entry);\n }\n return entries.reverse();\n };\n // Snapshot metadata can precede the context boundary: read only the newest plan and, when asked, checkpoint artifact.\n const policyEntries = async (execution: PoHeadlessExecutionContext, withCheckpoint: boolean) => {\n const entries = [\n ...(await execution.session.entries({\n type: 'custom',\n customType: PLAN_DOCUMENT_ENTRY,\n limit: 1,\n })),\n ] as unknown as CompactionPolicyEntry[];\n if (withCheckpoint) {\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n if (!latestCheckpointArtifactEntry([entry])) continue;\n entries.push(entry);\n break;\n }\n }\n return entries;\n };\n const contextBranch = async (execution: PoHeadlessExecutionContext) => {\n const entries: CompactionPolicyEntry[] = [];\n let foundLeaf = false;\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n const isLeaf = leaf([entry]) !== 'root';\n // Custom journals do not contribute model context. Keep only the newest leaf identity.\n if (entry.type !== 'custom' || (!foundLeaf && isLeaf)) entries.push(entry);\n if (isLeaf) foundLeaf = true;\n if (entry.type === 'compaction' || customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE) break;\n }\n return entries.reverse();\n };\n const canonical = async (execution: PoHeadlessExecutionContext, entries: CompactionPolicyEntry[]) => {\n if (!execution.session.contextMessages) throw new Error('Canonical context is unavailable for autocompact.');\n return projectContextMessages(\n (await execution.session.contextMessages()) as unknown as AutocompactMessage[],\n entries,\n ).messages;\n };\n // History is a convenience copy: its failure is reported once per session and never touches compaction state.\n // Never await this inside a queued job; it queues behind the job that schedules it.\n const scheduleMirror = (execution: PoHeadlessExecutionContext) => {\n if (mirrorQueued) return;\n mirrorQueued = true;\n void enqueue(async () => {\n mirrorQueued = false;\n try {\n await mirrorCompactionHistory(\n artifactRoot(execution.sessionId, execution.environment),\n await matching(execution, isHistoryEntry),\n );\n } catch (error) {\n const warn = historyWarnedSession !== execution.sessionId;\n historyWarnedSession = execution.sessionId;\n await Promise.allSettled([\n Promise.resolve().then(() =>\n telemetry.recordWarning(AUTOCOMPACT_EVENT.historyWriteFailed, error, attributes()),\n ),\n ...(warn\n ? [\n Promise.resolve().then(() =>\n execution.client.notify({\n body: `Po autocompact could not save compaction history: ${error instanceof Error ? error.message : String(error)}`,\n level: 'warning',\n }),\n ),\n ]\n : []),\n ]);\n }\n }).finally(() => {\n mirrorQueued = false;\n });\n };\n const contributionSnapshot = async (execution: PoHeadlessExecutionContext) => {\n const result = readContextContributionsSnapshot(contributions);\n for (const error of result.errors) {\n await execution.client.notify({\n body: `Po autocompact context contribution degraded (${error.source}/${error.id}): ${error.message}`,\n level: 'warning',\n });\n await telemetry.recordWarning(AUTOCOMPACT_EVENT.contextContributionDegraded, new Error(error.message), {\n ...attributes(),\n 'autocompact.context_contribution.source': error.source,\n 'autocompact.context_contribution.id': error.id,\n 'autocompact.context_contribution.order': error.order,\n });\n }\n return result;\n };\n const runtimeState = async (\n execution: PoHeadlessExecutionContext,\n entries: CompactionPolicyEntry[],\n version: number,\n appendMessage: PoHeadlessExecutionContext['session']['appendMessage'] = checkpointBoundary?.appendMessage.bind(\n checkpointBoundary,\n ),\n ) => {\n const saved = runtimeStateSnapshot(entries, await contributionSnapshot(execution));\n if (!alive(version)) return;\n await appendMessage?.({\n type: RUNTIME_STATE_MESSAGE_TYPE,\n text: formatRuntimeState(saved),\n display: false,\n details: { version: 2, ...saved },\n });\n return {\n 'autocompact.runtime.plan_present': Boolean(saved.planPath),\n 'autocompact.runtime.contribution_count': saved.contributions.length,\n 'autocompact.runtime.contribution_error_count': saved.contributionErrors.length,\n };\n };\n const summaryModel = async (execution: PoHeadlessExecutionContext, configuration: ReturnType<typeof configured>) => {\n const ownReference = configuration.agent?.model ? parseModelReference(configuration.agent.model) : undefined;\n const candidate = ownReference ? `${ownReference.provider}/${ownReference.modelId}` : undefined;\n const reference =\n candidate && execution.textCompletion!.available(candidate)\n ? candidate\n : execution.model\n ? `${execution.model.provider}/${execution.model.id}`\n : '';\n const thinking =\n configuration.agent?.thinking ??\n (reference === candidate ? ownReference?.thinking : undefined) ??\n (await execution.session.readModelSettings?.())?.thinkingLevel;\n return { reference, thinking };\n };\n // Manual compaction summarizes stored entries, which still hold everything this extension only projected away.\n // Commit a checkpoint now instead, folding what arrived since this cycle's staged summary the way pass 3 does.\n const manualCompaction = async (event: { instructions?: unknown }, execution: PoHeadlessExecutionContext) => {\n const configuration = configured(execution);\n if (!configuration.enabled || !execution.textCompletion?.summarize) return;\n try {\n const entries = await contextBranch(execution);\n const pinned = await policyEntries(execution, state.pass > 1);\n const messages = await canonical(execution, entries);\n const delta = state.pass > 1 && previousSnapshot ? tailAfter(previousSnapshot, messages) : undefined;\n const previous = state.pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(pinned)) : undefined;\n const { reference, thinking } = await summaryModel(execution, configuration);\n const instructions = checkpointInstructions(3, {\n plan: latestPlanSnapshot(pinned),\n contextContributions: await contributionSnapshot(execution),\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n });\n const { summary } = parseCheckpointDecision(\n await execution.textCompletion.summarize(reference, {\n messages: (delta ?? messages) as unknown as Record<string, unknown>[],\n instructions:\n typeof event.instructions === 'string' && event.instructions.trim()\n ? `${instructions}\\n\\n${event.instructions}`\n : instructions,\n ...(previous ? { previousSummary: previous } : {}),\n ...(thinking ? { thinkingLevel: thinking } : {}),\n ...(execution.signal ? { signal: execution.signal } : {}),\n }),\n );\n if (!isStructuredCheckpoint(summary)) throw new Error('Summarization returned an incomplete checkpoint.');\n const files = mergeFileDetails(state, fileOperationsFromMessages(messages));\n const usage = await execution.session.contextUsage?.();\n return {\n compaction: {\n summary: withCanonicalFileSections(summary, files),\n tokensBefore: usage?.tokens ?? 0,\n retainedTail: [],\n details: files,\n },\n };\n } catch (error) {\n // The host falls back to native compaction, whose own failure would hide this reason.\n await execution.client.notify({\n body: `Po autocompact manual compaction failed: ${error instanceof Error ? error.message : String(error)}`,\n level: 'error',\n });\n throw error;\n }\n };\n const resetCycle = () => {\n state.phase = 'waiting';\n state.checkpointQueue = [];\n state.exhaustedPasses = [];\n state.invalidAttempts = 0;\n state.baselinePending = true;\n state.cycle += 1;\n state.pass = 1;\n delete state.lastAttemptLeafId;\n delete state.latestCheckpointSnapshotLeafId;\n clear();\n previousSnapshot = undefined;\n };\n const applyReady = async (\n execution: PoHeadlessExecutionContext,\n version: number,\n appendMessage: NonNullable<typeof checkpointBoundary>['appendMessage'],\n ): Promise<boolean> => {\n if (state.phase !== 'checkpoint_ready' || !state.pendingCheckpoint || !state.requestId || !state.snapshotLeafId)\n return false;\n const decision = parseCheckpointDecision(state.pendingCheckpoint);\n if (!isStructuredCheckpoint(decision.summary)) {\n await fail(execution, version, new Error('Summarization returned an incomplete checkpoint.'), true, 'validation');\n return false;\n }\n const entries = await contextBranch(execution);\n const messages = await canonical(execution, entries);\n if (!alive(version)) return false;\n // Persisted legacy pending summaries lack canonical evidence. Retry rather than fabricate a retained tail.\n const tail = snapshot && tailAfter(snapshot, messages);\n if (!tail) {\n await fail(\n execution,\n version,\n new Error('Canonical checkpoint evidence changed; summary must be regenerated.'),\n false,\n 'evidence_changed',\n );\n return false;\n }\n const pass = state.pass;\n if (pass === 1 || (pass === 2 && decision.shouldCompact !== true)) {\n await execution.session.appendCustomEntry(CHECKPOINT_MESSAGE_TYPE, {\n ...checkpointRequestDetails(state.cycle, pass, state.requestId),\n summary: decision.summary,\n });\n if (!alive(version)) return false;\n previousSnapshot = snapshot;\n state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;\n state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);\n state.pass = pass === 1 ? 2 : 3;\n state.phase = 'waiting';\n state.invalidAttempts = 0;\n clear();\n await persist(execution, version);\n scheduleMirror(execution);\n return false;\n }\n const files = mergeFileDetails(state, fileOperationsFromMessages(messages));\n const details: AutocompactContextDetails = {\n ...files,\n poAutocompact: {\n version: STATE_VERSION,\n cycle: state.cycle,\n pass,\n requestId: state.requestId,\n snapshotLeafId: state.snapshotLeafId,\n tokensBefore: state.snapshotTokens ?? 0,\n },\n retainedMessages: tail,\n };\n const idle = (await execution.session.activity()).isIdle;\n if (!alive(version)) return false;\n // The marker heads native context, so native compaction and context reads skip everything before it.\n const id = await appendMessage(\n {\n type: CONTEXT_MESSAGE_TYPE,\n text: withCanonicalFileSections(decision.summary, files),\n display: false,\n details,\n },\n { resetContext: { retainedMessages: tail as unknown as Record<string, unknown>[] } },\n );\n if (!alive(version) || !id) return false;\n await execution.session.setLabel?.(id, `autocompact:c${state.cycle}:p${pass}`);\n if (!alive(version)) return false;\n const runtimeAttributes = await runtimeState(\n execution,\n await policyEntries(execution, false),\n version,\n appendMessage,\n );\n if (!alive(version)) return false;\n const committedAttributes = attributes();\n state.readFiles = files.readFiles;\n state.modifiedFiles = files.modifiedFiles;\n resetCycle();\n await persist(execution, version);\n scheduleMirror(execution);\n if (!alive(version)) return false;\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextCommitted, {\n ...committedAttributes,\n 'autocompact.message_count.before': messages.length,\n 'autocompact.message_count.retained': tail.length,\n 'autocompact.apply_mode': idle ? 'idle' : 'turn_end',\n ...runtimeAttributes,\n });\n if (idle && alive(version))\n await execution.session.admitPrompt?.(\n \"Asynchronous compaction completed. Continue from the compacted checkpoint's immediate next action without repeating completed work.\",\n 'steer',\n undefined,\n `${RESUME_MESSAGE_TYPE}:${details.poAutocompact.requestId}`,\n );\n return true;\n };\n const ensureCheckpointBoundary = (execution: PoHeadlessExecutionContext) => {\n if (checkpointBoundary) return;\n if (!execution.session.registerCheckpointBoundary) throw new Error('Native checkpoint boundaries are unavailable.');\n checkpointBoundary = execution.session.registerCheckpointBoundary(async (boundary) => {\n if (!active || navigating || boundary.signal?.aborted) return;\n const current = context ?? execution;\n await enqueue(() =>\n boundary.signal?.aborted ? Promise.resolve() : progress(current, true, boundary.appendMessage.bind(boundary)),\n );\n });\n };\n const advance = async (\n execution: PoHeadlessExecutionContext,\n allowBusy = false,\n appendMessage = checkpointBoundary?.appendMessage.bind(checkpointBoundary),\n ) => {\n const version = generation;\n context = execution;\n const activity = await execution.session.activity();\n if (!alive(version) || activity.hasPendingMessages) return;\n if (appendMessage && (activity.isIdle || allowBusy)) {\n if (await applyReady(execution, version, appendMessage)) return;\n }\n if (!alive(version) || state.phase !== 'waiting') return;\n const configuration = configured(execution);\n if (!configuration.enabled || !execution.session.contextUsage || !execution.textCompletion?.summarize) return;\n const usage = await execution.session.contextUsage();\n if (\n !alive(version) ||\n !usage ||\n typeof usage.tokens !== 'number' ||\n !Number.isFinite(usage.tokens) ||\n usage.tokens < 0\n )\n return;\n const tokens = usage.tokens;\n const thresholds = effectiveThresholds(\n usage.contextWindow,\n state.baselineTokens,\n configuration.ratios,\n resolveModelTokenOverrides(execution.model, configuration.overrides),\n );\n if (\n !state.baselinePending &&\n !state.checkpointQueue.length &&\n !([1, 2, 3] as const).some(\n (pass) => pass >= state.pass && !state.exhaustedPasses.includes(pass) && tokens >= thresholds[pass],\n )\n )\n return;\n const entries = await contextBranch(execution);\n if (!alive(version)) return;\n if (state.baselinePending) {\n if (!baselineUsageIsSettled(entries)) return;\n state.baselineTokens = usage.tokens;\n state.baselinePending = false;\n await persist(execution, version);\n return;\n }\n const currentLeaf = leaf(entries);\n if (currentLeaf === state.lastAttemptLeafId) return;\n for (const pass of [1, 2, 3] as const) {\n if (\n pass >= state.pass &&\n !state.checkpointQueue.includes(pass) &&\n !state.exhaustedPasses.includes(pass) &&\n usage.tokens >= thresholds[pass]\n )\n state.checkpointQueue.push(pass);\n }\n const pass = state.checkpointQueue[0];\n if (!pass) return;\n state.pass = pass;\n const checkpointEntries = await policyEntries(execution, pass > 1);\n const messages = await canonical(execution, entries);\n const steering = await contributionSnapshot(execution);\n if (!alive(version)) return;\n snapshot = messages;\n const previous =\n pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(checkpointEntries)) : undefined;\n const requestId = createRequestId(execution.sessionId, state.cycle, pass, currentLeaf);\n state.phase = 'checkpoint_pending';\n state.requestId = requestId;\n state.snapshotLeafId = currentLeaf;\n state.snapshotTokens = usage.tokens;\n delete state.lastAttemptLeafId;\n delete state.pendingCheckpoint;\n await persist(execution, version);\n if (!alive(version)) return;\n degraded = false;\n controller?.abort();\n controller = new AbortController();\n const signal = controller.signal;\n const requestAttributes = { ...attributes(), 'autocompact.message_count.before': messages.length };\n const delta = previousSnapshot ? tailAfter(previousSnapshot, messages) : undefined;\n let failureKind: 'configuration' | 'unknown' | 'persistence' = 'configuration';\n const completion = telemetry\n .runInSpan('po_autocompact.checkpoint', requestAttributes, async () => {\n const { reference, thinking } = await summaryModel(execution, configuration);\n failureKind = 'unknown';\n if (!alive(version) || signal.aborted) return '';\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, requestAttributes);\n return execution.textCompletion!.summarize!(reference, {\n messages: (pass > 1 && delta ? delta : messages) as unknown as Record<string, unknown>[],\n instructions: checkpointInstructions(pass, {\n plan: latestPlanSnapshot(checkpointEntries),\n contextContributions: steering,\n readFiles: state.readFiles,\n modifiedFiles: state.modifiedFiles,\n }),\n ...(previous ? { previousSummary: previous } : {}),\n ...(thinking ? { thinkingLevel: thinking } : {}),\n signal,\n });\n })\n .then(async (summary) => {\n await enqueue(async () => {\n if (!alive(version) || signal.aborted || state.requestId !== requestId) return;\n if (!summary.trim()) {\n await fail(\n execution,\n version,\n new Error('Summarization returned an empty checkpoint.'),\n false,\n 'empty_checkpoint',\n );\n return;\n }\n state.phase = 'checkpoint_ready';\n state.pendingCheckpoint = summary.trim();\n failureKind = 'persistence';\n await persist(execution, version);\n failureKind = 'unknown';\n if (!alive(version)) return;\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {\n ...requestAttributes,\n 'autocompact.checkpoint.characters': summary.length,\n });\n if ((await execution.session.activity()).isIdle && alive(version)) await progress(execution);\n });\n })\n .catch(async (error: unknown) => {\n await enqueue(async () => {\n if (alive(version) && state.requestId === requestId)\n await fail(execution, version, error, false, failureKind);\n });\n });\n work.add(completion);\n void completion.then(\n () => work.delete(completion),\n () => work.delete(completion),\n );\n };\n const progress = async (\n execution: PoHeadlessExecutionContext,\n allowBusy = false,\n appendMessage?: Parameters<typeof advance>[2],\n ) => {\n const version = generation;\n try {\n ensureCheckpointBoundary(execution);\n await advance(execution, allowBusy, appendMessage);\n } catch (error) {\n try {\n await fail(execution, version, error, false, 'persistence');\n } finally {\n // Infrastructure failures can recover without a new conversation leaf.\n if (alive(version)) delete state.lastAttemptLeafId;\n }\n }\n };\n const load = async (execution: PoHeadlessExecutionContext) => {\n if (!active) return;\n navigating = false;\n generation += 1;\n const version = generation;\n controller?.abort(new Error('Autocompact session generation changed.'));\n controller = undefined;\n context = execution;\n applied.clear();\n invalid.clear();\n const saved = await execution.session.customSnapshot?.(STATE_CUSTOM_TYPE);\n if (!alive(version)) return;\n const entry = (saved?.available ? saved.entry : undefined) as unknown as CompactionPolicyEntry | undefined;\n const data =\n entry?.type === 'custom' && entry.data && typeof entry.data === 'object'\n ? (entry.data as Record<string, unknown>)\n : undefined;\n state = parseState(data) ?? createInitialState();\n lastNativeCompactionId = typeof data?.nativeLastCompactionId === 'string' ? data.nativeLastCompactionId : undefined;\n const validMessages = (value: unknown): value is AutocompactMessage[] =>\n Array.isArray(value) &&\n value.every((message) => message && typeof message === 'object' && typeof message.role === 'string');\n snapshot = validMessages(data?.nativeSnapshot) ? data.nativeSnapshot : undefined;\n previousSnapshot = validMessages(data?.nativePreviousSnapshot) ? data.nativePreviousSnapshot : undefined;\n // A marker can commit before its following state entry. Recover only the exact\n // request after the saved state, rather than retrying against already-compacted evidence.\n if (entry?.id && state.phase === 'checkpoint_ready' && state.requestId) {\n const artifacts = await matching(\n execution,\n (item) =>\n (item.type === 'custom' && item.customType === CHECKPOINT_MESSAGE_TYPE) ||\n customMessage(item)?.customType === CONTEXT_MESSAGE_TYPE,\n entry?.id,\n );\n const committed = artifacts.findLast((item) => {\n const message = item.type === 'message' ? item.message : undefined;\n if (message?.role !== 'custom' || message.customType !== CONTEXT_MESSAGE_TYPE) return false;\n const details = contextDetailsFromUnknown(message.details);\n return (\n details !== undefined &&\n details.poAutocompact.requestId === state.requestId &&\n details.poAutocompact.cycle === state.cycle &&\n details.poAutocompact.pass === state.pass &&\n details.poAutocompact.snapshotLeafId === state.snapshotLeafId &&\n isStructuredCheckpoint(checkpointSummaryFromEntry(item) ?? '')\n );\n });\n if (committed?.type === 'message' && committed.message.role === 'custom') {\n const details = contextDetailsFromUnknown(committed.message.details)!;\n state.readFiles = details.readFiles;\n state.modifiedFiles = details.modifiedFiles;\n resetCycle();\n await persist(execution, version);\n } else {\n const staged = artifacts.findLast((item) => {\n if (item.type !== 'custom' || item.customType !== CHECKPOINT_MESSAGE_TYPE) return false;\n const details = item.data as Record<string, unknown> | undefined;\n return (\n details?.version === STATE_VERSION &&\n details.requestId === state.requestId &&\n details.cycle === state.cycle &&\n details.pass === state.pass &&\n isStructuredCheckpoint(checkpointSummaryFromEntry(item) ?? '')\n );\n });\n if (staged && (state.pass === 1 || state.pass === 2)) {\n previousSnapshot = snapshot;\n state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;\n state.checkpointQueue = state.checkpointQueue.filter((pass) => pass !== state.pass);\n state.pass = state.pass === 1 ? 2 : 3;\n state.phase = 'waiting';\n state.invalidAttempts = 0;\n clear();\n await persist(execution, version);\n }\n }\n }\n if (state.phase !== 'waiting' && (state.phase !== 'checkpoint_ready' || !snapshot)) {\n // ponytail: snapshot-free pending work regenerates after restart; durable prefix reconstruction can avoid this cost later.\n state.phase = 'waiting';\n clear();\n delete state.lastAttemptLeafId;\n await persist(execution, version);\n }\n if (!alive(version)) return;\n const progressed = enqueue(() => progress(execution));\n scheduleMirror(execution);\n await progressed;\n };\n const restore = async (execution: PoHeadlessExecutionContext) => {\n const version = generation + 1;\n try {\n await load(execution);\n } catch (error) {\n await fail(execution, version, error);\n }\n };\n const hooks: PoHeadlessHook[] = [\n { event: 'session_start', handle: (_event, execution) => restore(execution) },\n {\n event: 'session_tree',\n handle: (event, execution) => {\n if (!active) return;\n if (event.status === 'started') {\n navigating = true;\n generation += 1;\n controller?.abort(new Error('Autocompact navigation started.'));\n return;\n }\n return restore(execution);\n },\n },\n {\n event: 'turn_end',\n handle: (_event, execution) => enqueue(() => progress(execution)),\n },\n { event: 'agent_settled', handle: (_event, execution) => enqueue(() => progress(execution)) },\n {\n event: 'session_before_compact',\n handle: (event, execution) => {\n if (!active || navigating) return;\n if (event.reason === 'manual') return manualCompaction(event, execution);\n return !degraded &&\n configured(execution).enabled &&\n event.reason === 'threshold' &&\n (state.phase === 'checkpoint_pending' || state.phase === 'checkpoint_ready')\n ? { cancel: true }\n : undefined;\n },\n },\n {\n event: 'context',\n async handle(event, execution) {\n if (!active || navigating || !Array.isArray(event.messages)) return;\n const started = Date.now();\n try {\n const version = generation;\n const entries = await contextBranch(execution);\n if (!alive(version)) return;\n const projection = projectContextMessages(event.messages as AutocompactMessage[], entries);\n if (projection.invalidMarker) {\n const id = leaf(entries);\n if (!invalid.has(id)) {\n invalid.add(id);\n await telemetry.recordError(\n AUTOCOMPACT_EVENT.contextMarkerInvalid,\n new Error('Po autocompact context marker is malformed.'),\n { ...attributes(), 'autocompact.leaf_id': id },\n );\n }\n return;\n }\n if (!projection.marker) return;\n if (!applied.has(projection.marker.requestId)) {\n applied.add(projection.marker.requestId);\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextApplied, {\n ...attributes(),\n 'autocompact.request.id': projection.marker.requestId,\n 'autocompact.cycle': projection.marker.cycle,\n 'autocompact.pass': projection.marker.pass,\n 'autocompact.snapshot_leaf_id': projection.marker.snapshotLeafId,\n 'autocompact.tokens_before': projection.marker.tokensBefore,\n 'autocompact.message_count.before': event.messages.length,\n 'autocompact.message_count.after': projection.messages.length,\n 'autocompact.message_count.retained': projection.retainedMessageCount,\n });\n }\n return alive(version) ? { messages: projection.messages } : undefined;\n } finally {\n const hookMs = Date.now() - started;\n if (active && hookMs >= SLOW_CONTEXT_HOOK_MS)\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextHookSlow, {\n ...attributes(),\n hook_ms: hookMs,\n 'autocompact.message_count': event.messages.length,\n });\n }\n },\n },\n {\n event: 'session_compact',\n handle: (event, execution) => {\n if (\n !active ||\n event.status !== 'completed' ||\n typeof event.entryId !== 'string' ||\n event.entryId === lastNativeCompactionId\n )\n return;\n const observedGeneration = generation;\n return enqueue(async () => {\n const entries = (await execution.session.entries({\n type: 'compaction',\n limit: 1,\n })) as unknown as CompactionPolicyEntry[];\n const compacted = entries[0];\n if (\n !alive(observedGeneration) ||\n !compacted ||\n compacted.type !== 'compaction' ||\n compacted.id !== event.entryId ||\n compacted.id === lastNativeCompactionId\n )\n return;\n generation += 1;\n const version = generation;\n controller?.abort(new Error('Native compaction superseded checkpoint.'));\n controller = undefined;\n lastNativeCompactionId = compacted.id;\n const files = mergeFileDetails(\n state,\n undefined,\n fileDetailsFromUnknown('details' in compacted ? compacted.details : undefined),\n );\n state.readFiles = files.readFiles;\n state.modifiedFiles = files.modifiedFiles;\n await execution.session.setLabel?.(compacted.id, `autocompact:c${state.cycle}:external`);\n if (!alive(version)) return;\n const plan = (await execution.session.entries({\n type: 'custom',\n customType: PLAN_DOCUMENT_ENTRY,\n limit: 1,\n })) as unknown as CompactionPolicyEntry[];\n const runtimeAttributes = await runtimeState(execution, plan, version);\n if (!alive(version)) return;\n const nativeAttributes = attributes();\n resetCycle();\n await persist(execution, version);\n scheduleMirror(execution);\n if (alive(version))\n await telemetry.recordEvent(AUTOCOMPACT_EVENT.nativeCompactionCompleted, {\n ...nativeAttributes,\n 'autocompact.native.reason': typeof event.reason === 'string' ? event.reason : 'unknown',\n 'autocompact.native.from_extension': 'fromHook' in compacted && compacted.fromHook === true,\n 'autocompact.tokens_before': compacted.tokensBefore,\n ...runtimeAttributes,\n });\n });\n },\n },\n ];\n return {\n hooks,\n plugin(cordis) {\n cordis.inject([PO_UI_HUB_SERVICE], (injected) => {\n const contribution = requirePoUiHub(injected).registerFooter({\n source: FOOTER_SOURCE,\n id: 'autocompact',\n order: FOOTER_ORDER,\n });\n footer = contribution;\n if (context && active) refreshStatus(context);\n return () => {\n contribution.dispose();\n if (footer === contribution) footer = undefined;\n };\n });\n cordis.inject([PO_CONTEXT_CONTRIBUTIONS_SERVICE], (injected) => {\n const service = requirePoContextContributions(injected);\n contributions = service;\n return () => {\n if (contributions === service) contributions = undefined;\n };\n });\n },\n start: restore,\n async stop() {\n active = false;\n checkpointBoundary?.dispose();\n checkpointBoundary = undefined;\n generation += 1;\n controller?.abort(new Error('Autocompact is shutting down.'));\n await Promise.allSettled([...work, serial]);\n context?.client.setStatus(STATUS_KEY, undefined);\n footer?.update(undefined);\n footer = undefined;\n context = undefined;\n contributions = undefined;\n await telemetry.shutdown();\n },\n };\n}\n","import { defineRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { admittedModes } from '../../../../services/admittedModes';\nimport { createAutocompactTelemetry } from '../../../../services/autocompactTelemetry';\nimport { createNativeAutocompact } from '../../../../services/nativeAutocompact';\n\nexport default defineRoot(({ agent, context }: PoServerPluginContext) => {\n const runtime = createNativeAutocompact({\n telemetry: createAutocompactTelemetry({ env: agent?.context.environment, cwd: agent?.context.cwd }),\n modes: admittedModes(context),\n });\n return { value: runtime, services: [runtime.plugin], onDispose: runtime.stop };\n});\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'agent_settled')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'context')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_before_compact')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_compact')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_start')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'session_tree')!,\n);\n","import { defineHook, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { NativeAutocompactRuntime } from '../../../../../services/nativeAutocompact/type';\n\nexport default defineHook(({ root }: WithRoot<PoServerPluginContext, NativeAutocompactRuntime>) =>\n root.hooks.find((hook) => hook.event === 'turn_end')!,\n);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport hookAgentSettled from '../src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server';\nimport hookContext from '../src/extensions/workspaces/sessions/(backend)/hook/context.server';\nimport hookSessionBeforeCompact from '../src/extensions/workspaces/sessions/(backend)/hook/session-before-compact.server';\nimport hookSessionCompact from '../src/extensions/workspaces/sessions/(backend)/hook/session-compact.server';\nimport hookSessionStart from '../src/extensions/workspaces/sessions/(backend)/hook/session-start.server';\nimport hookSessionTree from '../src/extensions/workspaces/sessions/(backend)/hook/session-tree.server';\nimport hookTurnEnd from '../src/extensions/workspaces/sessions/(backend)/hook/turn-end.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-autocompact',\n providerOverrides: composeServerProviderOverrides(rootSession),\n injects: composeRootInjects({ session: [rootSession] }),\n session: async (context) => {\n const scopeSession = await context.scopeRoot('session', rootSession, context);\n const contextSession = { ...context, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeSession),\n get hooks(): PoServerSessionPlugin['hooks'] { return [via({ event: 'agent_settled' }, at(hookAgentSettled, contextSession)), via({ event: 'context' }, at(hookContext, contextSession)), via({ event: 'session_before_compact' }, at(hookSessionBeforeCompact, contextSession)), via({ event: 'session_compact' }, at(hookSessionCompact, contextSession)), via({ event: 'session_start' }, at(hookSessionStart, contextSession)), via({ event: 'session_tree' }, at(hookSessionTree, contextSession)), via({ event: 'turn_end' }, at(hookTurnEnd, contextSession))]; },\n services: [...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;;;;ACOA,MAAM,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AAI;AACpE,MAAM,OAAU,UAAmC,UAChD,UAAU,KAAA,IAAY,KAAA,IAAY;CAAE,GAAG;CAAU,GAAI;AAAiB;AAEzE,MAAa,eAAe,mBAAmB;CAC7C,MAAM;CACN,mBAAmB,+BAA+BA,mBAAW;CAC7D,SAAS,mBAAmB,EAAE,SAAS,CAACA,mBAAW,EAAE,CAAC;CACtD,SAAS,OAAO,YAAY;EAC1B,MAAM,eAAe,MAAM,QAAQ,UAAU,WAAWA,qBAAa,OAAO;EAC5E,MAAM,iBAAiB;GAAE,GAAG;GAAS,MAAM,aAAa;EAAM;EAC9D,OAAO;GACL,GAAG,iBAAiB,YAAY;GAChC,IAAI,QAAwC;IAAE,OAAO;KAAC,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,8BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,UAAU,GAAG,GAAGC,wBAAa,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,yBAAyB,GAAG,GAAGC,uCAA0B,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,kBAAkB,GAAG,GAAGC,gCAAoB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,8BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,eAAe,GAAG,GAAGC,6BAAiB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,WAAW,GAAG,GAAGC,yBAAa,cAAc,CAAC;IAAC;GAAG;GACtiB,UAAU,CAAC,GAAI,aAAa,YAAY,CAAC,CAAE;GAC3C,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EACvG;CACF;AACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-autocompact",
3
- "version": "0.0.0-alpha.113",
3
+ "version": "0.0.0-alpha.114",
4
4
  "description": "Iterative context compaction and checkpoint summaries for Po headless agent sessions.",
5
5
  "keywords": [
6
6
  "ai",
@@ -59,15 +59,15 @@
59
59
  "access": "public"
60
60
  },
61
61
  "dependencies": {
62
- "@agimon-ai/po-artifact": "0.0.0-alpha.112",
63
- "@agimon-ai/po-config": "0.0.0-alpha.113",
64
- "@agimon-ai/po-core": "0.0.0-alpha.113",
65
- "@agimon-ai/po-web-components": "0.0.0-alpha.113",
62
+ "@agimon-ai/po-artifact": "0.0.0-alpha.113",
63
+ "@agimon-ai/po-config": "0.0.0-alpha.114",
64
+ "@agimon-ai/po-core": "0.0.0-alpha.114",
65
+ "@agimon-ai/po-web-components": "0.0.0-alpha.114",
66
66
  "@deepseek-ai/cordis": "4.0.5",
67
67
  "minimatch": "10.2.6"
68
68
  },
69
69
  "devDependencies": {
70
- "@agimon-ai/po-build": "0.0.0-alpha.113",
70
+ "@agimon-ai/po-build": "0.0.0-alpha.114",
71
71
  "@earendil-works/pi-coding-agent": "1.5.0",
72
72
  "@types/node": "26.6.5",
73
73
  "@vitest/coverage-v8": "5.0.4",