@agimon-ai/po-autocompact 0.0.0-alpha.36 → 0.0.0-alpha.38

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.
@@ -49,6 +49,9 @@ function createAutocompactTelemetry(options = {}) {
49
49
  shutdown: () => telemetry.shutdown()
50
50
  };
51
51
  }
52
+ //#endregion
53
+ //#region src/constants/runtime.ts
54
+ const PLAN_DOCUMENT_ENTRY = "agent-harness-plan-document";
52
55
  const FOOTER_SOURCE = "po-autocompact";
53
56
  const STATUS_KEY = "po-autocompact";
54
57
  //#endregion
@@ -455,6 +458,18 @@ function createNativeAutocompact(dependencies = {}) {
455
458
  })))]);
456
459
  };
457
460
  const branch = async (execution) => await execution.session.entries();
461
+ const contextBranch = async (execution) => {
462
+ const entries = [];
463
+ let foundLeaf = false;
464
+ for await (const record of execution.session.entriesNewestFirst()) {
465
+ const entry = record;
466
+ const isLeaf = leaf([entry]) !== "root";
467
+ if (entry.type !== "custom" || !foundLeaf && isLeaf) entries.push(entry);
468
+ if (isLeaf) foundLeaf = true;
469
+ if (entry.type === "compaction" || require_compactionPolicy.customMessage(entry)?.customType === "po-autocompact-context") break;
470
+ }
471
+ return entries.reverse();
472
+ };
458
473
  const canonical = async (execution, entries) => {
459
474
  if (!execution.session.contextMessages) throw new Error("Canonical context is unavailable for autocompact.");
460
475
  return require_compactionPolicy.projectContextMessages(await execution.session.contextMessages(), entries).messages;
@@ -678,7 +693,7 @@ function createNativeAutocompact(dependencies = {}) {
678
693
  const configuration = configured(execution);
679
694
  if (!configuration.enabled || !execution.session.contextUsage || !execution.textCompletion?.summarize) return;
680
695
  const usage = await execution.session.contextUsage();
681
- const entries = await branch(execution);
696
+ const entries = await contextBranch(execution);
682
697
  if (!alive(version) || !usage || usage.tokens === null) return;
683
698
  if (state.baselinePending) {
684
699
  if (!require_compactionPolicy.baselineUsageIsSettled(entries)) return;
@@ -698,11 +713,22 @@ function createNativeAutocompact(dependencies = {}) {
698
713
  const pass = state.checkpointQueue[0];
699
714
  if (!pass) return;
700
715
  state.pass = pass;
716
+ const checkpointEntries = [...await execution.session.entries({
717
+ type: "custom",
718
+ customType: PLAN_DOCUMENT_ENTRY,
719
+ limit: 1
720
+ })];
721
+ if (pass > 1) for await (const record of execution.session.entriesNewestFirst()) {
722
+ const entry = record;
723
+ if (!require_compactionPolicy.latestCheckpointArtifactEntry([entry])) continue;
724
+ checkpointEntries.push(entry);
725
+ break;
726
+ }
701
727
  const messages = await canonical(execution, entries);
702
728
  const steering = await contributionSnapshot(execution);
703
729
  if (!alive(version)) return;
704
730
  snapshot = messages;
705
- const previous = pass > 1 ? require_compactionPolicy.checkpointSummaryFromEntry(require_compactionPolicy.latestCheckpointArtifactEntry(entries)) : void 0;
731
+ const previous = pass > 1 ? require_compactionPolicy.checkpointSummaryFromEntry(require_compactionPolicy.latestCheckpointArtifactEntry(checkpointEntries)) : void 0;
706
732
  const requestId = require_compactionPolicy.createRequestId(execution.sessionId, state.cycle, pass, currentLeaf);
707
733
  state.phase = "checkpoint_pending";
708
734
  state.requestId = requestId;
@@ -728,7 +754,7 @@ function createNativeAutocompact(dependencies = {}) {
728
754
  return execution.textCompletion.summarize(reference, {
729
755
  messages: pass > 1 && delta ? delta : messages,
730
756
  instructions: checkpointInstructions(pass, {
731
- plan: latestPlanSnapshot(entries),
757
+ plan: latestPlanSnapshot(checkpointEntries),
732
758
  contextContributions: steering,
733
759
  readFiles: state.readFiles,
734
760
  modifiedFiles: state.modifiedFiles
@@ -785,7 +811,11 @@ function createNativeAutocompact(dependencies = {}) {
785
811
  context = execution;
786
812
  applied.clear();
787
813
  invalid.clear();
788
- const entries = await branch(execution);
814
+ const entries = await execution.session.entries({
815
+ type: "custom",
816
+ customType: require_compactionPolicy.STATE_CUSTOM_TYPE,
817
+ limit: 1
818
+ });
789
819
  if (!alive(version)) return;
790
820
  const entry = entries.findLast((item) => item.type === "custom" && item.customType === "po-autocompact-state");
791
821
  const data = entry?.type === "custom" && entry.data && typeof entry.data === "object" ? entry.data : void 0;
@@ -795,7 +825,8 @@ function createNativeAutocompact(dependencies = {}) {
795
825
  snapshot = validMessages(data?.nativeSnapshot) ? data.nativeSnapshot : void 0;
796
826
  previousSnapshot = validMessages(data?.nativePreviousSnapshot) ? data.nativePreviousSnapshot : void 0;
797
827
  if (state.phase === "checkpoint_ready" && state.requestId) {
798
- const artifacts = entries.slice(entry ? entries.indexOf(entry) + 1 : 0);
828
+ const history = await branch(execution);
829
+ const artifacts = history.slice(entry ? history.findIndex((item) => item.id === entry.id) + 1 : 0);
799
830
  const committed = artifacts.findLast((item) => {
800
831
  const message = item.type === "message" ? item.message : void 0;
801
832
  if (message?.role !== "custom" || message.customType !== "po-autocompact-context") return false;
@@ -884,7 +915,7 @@ function createNativeAutocompact(dependencies = {}) {
884
915
  const started = Date.now();
885
916
  try {
886
917
  const version = generation;
887
- const entries = await branch(execution);
918
+ const entries = await contextBranch(execution);
888
919
  if (!alive(version)) return;
889
920
  const projection = require_compactionPolicy.projectContextMessages(event.messages, entries);
890
921
  if (projection.invalidMarker) {
@@ -930,9 +961,11 @@ function createNativeAutocompact(dependencies = {}) {
930
961
  if (!active || event.status !== "completed" || typeof event.entryId !== "string" || event.entryId === lastNativeCompactionId) return;
931
962
  const observedGeneration = generation;
932
963
  return enqueue(async () => {
933
- const entries = await branch(execution);
934
- const compacted = entries.findLast((entry) => entry.type === "compaction");
935
- if (!alive(observedGeneration) || !compacted || compacted.id !== event.entryId || compacted.id === lastNativeCompactionId) return;
964
+ const compacted = (await execution.session.entries({
965
+ type: "compaction",
966
+ limit: 1
967
+ }))[0];
968
+ if (!alive(observedGeneration) || !compacted || compacted.type !== "compaction" || compacted.id !== event.entryId || compacted.id === lastNativeCompactionId) return;
936
969
  generation += 1;
937
970
  const version = generation;
938
971
  controller?.abort(/* @__PURE__ */ new Error("Native compaction superseded checkpoint."));
@@ -943,7 +976,12 @@ function createNativeAutocompact(dependencies = {}) {
943
976
  state.modifiedFiles = files.modifiedFiles;
944
977
  await execution.session.setLabel?.(compacted.id, `autocompact:c${state.cycle}:external`);
945
978
  if (!alive(version)) return;
946
- const runtimeAttributes = await runtimeState(execution, entries, version);
979
+ const plan = await execution.session.entries({
980
+ type: "custom",
981
+ customType: PLAN_DOCUMENT_ENTRY,
982
+ limit: 1
983
+ });
984
+ const runtimeAttributes = await runtimeState(execution, plan, version);
947
985
  if (!alive(version)) return;
948
986
  const nativeAttributes = attributes();
949
987
  resetCycle();
@@ -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","projectContextMessages","artifactRoot","RUNTIME_STATE_MESSAGE_TYPE","checkpointSummaryFromEntry","latestCheckpointArtifactEntry","parseCheckpointDecision","isStructuredCheckpoint","mergeFileDetails","fileOperationsFromMessages","withCanonicalFileSections","CHECKPOINT_MESSAGE_TYPE","checkpointRequestDetails","CONTEXT_MESSAGE_TYPE","RESUME_MESSAGE_TYPE","baselineUsageIsSettled","effectiveThresholds","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 { createPoTelemetry, type PoTelemetry, type PoTelemetryOptions } 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(event: AutocompactEventName, error: unknown, attributes?: AutocompactEventAttributes): 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) => telemetry.recordError(event, error, attributes),\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/** 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 { FOOTER_ORDER, FOOTER_SOURCE, SLOW_CONTEXT_HOOK_MS, STATUS_KEY } 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 { mirrorCompactionHistory } from '../compactionHistory';\nimport {\n baselineUsageIsSettled,\n checkpointRequestDetails,\n checkpointSummaryFromEntry,\n contextDetailsFromUnknown,\n createInitialState,\n createRequestId,\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, attributes());\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 (execution: PoHeadlessExecutionContext, version: number, error: unknown, malformed = false) => {\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) =>\n Promise.resolve().then(() =>\n telemetry.recordError(\n malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed,\n failure,\n {\n ...eventAttributes,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS,\n },\n ),\n ),\n ),\n ]);\n };\n const branch = async (execution: PoHeadlessExecutionContext) =>\n (await execution.session.entries()) as unknown as CompactionPolicyEntry[];\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 branch(execution),\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 branch(execution);\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(entries)) : undefined;\n const { reference, thinking } = await summaryModel(execution, configuration);\n const instructions = checkpointInstructions(3, {\n plan: latestPlanSnapshot(entries),\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 (execution: PoHeadlessExecutionContext, version: number): 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);\n return false;\n }\n const entries = await branch(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(execution, version, new Error('Canonical checkpoint evidence changed; summary must be regenerated.'));\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 if (!execution.session.appendMessage) throw new Error('Checkpoint messages are unavailable.');\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 const id = await execution.session.appendMessage({\n type: CONTEXT_MESSAGE_TYPE,\n text: withCanonicalFileSections(decision.summary, files),\n display: false,\n details,\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 entries,\n version,\n execution.session.appendMessage.bind(execution.session),\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 const checkpointExecution = { ...execution, session: { ...execution.session, appendMessage } };\n if (await applyReady(checkpointExecution, version)) 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 const entries = await branch(execution);\n if (!alive(version) || !usage || usage.tokens === null) 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 const thresholds = effectiveThresholds(\n usage.contextWindow,\n state.baselineTokens,\n configuration.ratios,\n resolveModelTokenOverrides(execution.model, configuration.overrides),\n );\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 messages = await canonical(execution, entries);\n const steering = await contributionSnapshot(execution);\n if (!alive(version)) return;\n snapshot = messages;\n const previous = pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(entries)) : 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 const completion = telemetry\n .runInSpan('po_autocompact.checkpoint', requestAttributes, async () => {\n const { reference, thinking } = await summaryModel(execution, configuration);\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(entries),\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(execution, version, new Error('Summarization returned an empty checkpoint.'));\n return;\n }\n state.phase = 'checkpoint_ready';\n state.pendingCheckpoint = summary.trim();\n await persist(execution, version);\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) await fail(execution, version, error);\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);\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 entries = await branch(execution);\n if (!alive(version)) return;\n const entry = entries.findLast((item) => item.type === 'custom' && item.customType === STATE_CUSTOM_TYPE);\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 (state.phase === 'checkpoint_ready' && state.requestId) {\n const artifacts = entries.slice(entry ? entries.indexOf(entry) + 1 : 0);\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 branch(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 branch(execution);\n const compacted = entries.findLast((entry) => entry.type === 'compaction');\n if (\n !alive(observedGeneration) ||\n !compacted ||\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 runtimeAttributes = await runtimeState(execution, entries, 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":";;;;;;;;;;;;;;AAEA,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;AAsBA,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,eAAe,UAAU,YAAY,O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AAG,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.cjs","names":["createPoTelemetry","PO_CONTEXT_CONTRIBUTIONS_SERVICE","loadPoConfig","COMPACTION_ARTIFACT_DIRECTORY","customMessage","contextDetailsFromUnknown","checkpointSummaryFromEntry","openArtifact","ArtifactAccessError","readArtifactBytes","writeArtifactText","listArtifacts","removeArtifact","createInitialState","STATE_CUSTOM_TYPE","customMessage","projectContextMessages","artifactRoot","RUNTIME_STATE_MESSAGE_TYPE","checkpointSummaryFromEntry","latestCheckpointArtifactEntry","parseCheckpointDecision","isStructuredCheckpoint","mergeFileDetails","fileOperationsFromMessages","withCanonicalFileSections","CHECKPOINT_MESSAGE_TYPE","checkpointRequestDetails","CONTEXT_MESSAGE_TYPE","RESUME_MESSAGE_TYPE","baselineUsageIsSettled","effectiveThresholds","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 { createPoTelemetry, type PoTelemetry, type PoTelemetryOptions } 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(event: AutocompactEventName, error: unknown, attributes?: AutocompactEventAttributes): 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) => telemetry.recordError(event, error, attributes),\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/** 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 { 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, attributes());\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 (execution: PoHeadlessExecutionContext, version: number, error: unknown, malformed = false) => {\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) =>\n Promise.resolve().then(() =>\n telemetry.recordError(\n malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed,\n failure,\n {\n ...eventAttributes,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS,\n },\n ),\n ),\n ),\n ]);\n };\n const branch = async (execution: PoHeadlessExecutionContext) =>\n (await execution.session.entries()) as unknown as CompactionPolicyEntry[];\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 branch(execution),\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 branch(execution);\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(entries)) : undefined;\n const { reference, thinking } = await summaryModel(execution, configuration);\n const instructions = checkpointInstructions(3, {\n plan: latestPlanSnapshot(entries),\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 (execution: PoHeadlessExecutionContext, version: number): 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);\n return false;\n }\n const entries = await branch(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(execution, version, new Error('Canonical checkpoint evidence changed; summary must be regenerated.'));\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 if (!execution.session.appendMessage) throw new Error('Checkpoint messages are unavailable.');\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 const id = await execution.session.appendMessage({\n type: CONTEXT_MESSAGE_TYPE,\n text: withCanonicalFileSections(decision.summary, files),\n display: false,\n details,\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 entries,\n version,\n execution.session.appendMessage.bind(execution.session),\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 const checkpointExecution = { ...execution, session: { ...execution.session, appendMessage } };\n if (await applyReady(checkpointExecution, version)) 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 const entries = await contextBranch(execution);\n if (!alive(version) || !usage || usage.tokens === null) 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 const thresholds = effectiveThresholds(\n usage.contextWindow,\n state.baselineTokens,\n configuration.ratios,\n resolveModelTokenOverrides(execution.model, configuration.overrides),\n );\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 // Snapshot metadata can precede the context boundary, but is needed only when a checkpoint starts.\n const checkpointEntries = [\n ...(await execution.session.entries({\n type: 'custom',\n customType: PLAN_DOCUMENT_ENTRY,\n limit: 1,\n })),\n ] as unknown as CompactionPolicyEntry[];\n if (pass > 1) {\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n if (!latestCheckpointArtifactEntry([entry])) continue;\n checkpointEntries.push(entry);\n break;\n }\n }\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 const completion = telemetry\n .runInSpan('po_autocompact.checkpoint', requestAttributes, async () => {\n const { reference, thinking } = await summaryModel(execution, configuration);\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(execution, version, new Error('Summarization returned an empty checkpoint.'));\n return;\n }\n state.phase = 'checkpoint_ready';\n state.pendingCheckpoint = summary.trim();\n await persist(execution, version);\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) await fail(execution, version, error);\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);\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 entries = (await execution.session.entries({\n type: 'custom',\n customType: STATE_CUSTOM_TYPE,\n limit: 1,\n })) as unknown as CompactionPolicyEntry[];\n if (!alive(version)) return;\n const entry = entries.findLast((item) => item.type === 'custom' && item.customType === STATE_CUSTOM_TYPE);\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 (state.phase === 'checkpoint_ready' && state.requestId) {\n const history = await branch(execution);\n const artifacts = history.slice(entry ? history.findIndex((item) => item.id === entry.id) + 1 : 0);\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":";;;;;;;;;;;;;;AAEA,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;AAsBA,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,eAAe,UAAU,YAAY,OAAO,OAAO,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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"}
@@ -45,6 +45,9 @@ function createAutocompactTelemetry(options = {}) {
45
45
  shutdown: () => telemetry.shutdown()
46
46
  };
47
47
  }
48
+ //#endregion
49
+ //#region src/constants/runtime.ts
50
+ const PLAN_DOCUMENT_ENTRY = "agent-harness-plan-document";
48
51
  const FOOTER_SOURCE = "po-autocompact";
49
52
  const STATUS_KEY = "po-autocompact";
50
53
  //#endregion
@@ -451,6 +454,18 @@ function createNativeAutocompact(dependencies = {}) {
451
454
  })))]);
452
455
  };
453
456
  const branch = async (execution) => await execution.session.entries();
457
+ const contextBranch = async (execution) => {
458
+ const entries = [];
459
+ let foundLeaf = false;
460
+ for await (const record of execution.session.entriesNewestFirst()) {
461
+ const entry = record;
462
+ const isLeaf = leaf([entry]) !== "root";
463
+ if (entry.type !== "custom" || !foundLeaf && isLeaf) entries.push(entry);
464
+ if (isLeaf) foundLeaf = true;
465
+ if (entry.type === "compaction" || customMessage(entry)?.customType === "po-autocompact-context") break;
466
+ }
467
+ return entries.reverse();
468
+ };
454
469
  const canonical = async (execution, entries) => {
455
470
  if (!execution.session.contextMessages) throw new Error("Canonical context is unavailable for autocompact.");
456
471
  return projectContextMessages(await execution.session.contextMessages(), entries).messages;
@@ -674,7 +689,7 @@ function createNativeAutocompact(dependencies = {}) {
674
689
  const configuration = configured(execution);
675
690
  if (!configuration.enabled || !execution.session.contextUsage || !execution.textCompletion?.summarize) return;
676
691
  const usage = await execution.session.contextUsage();
677
- const entries = await branch(execution);
692
+ const entries = await contextBranch(execution);
678
693
  if (!alive(version) || !usage || usage.tokens === null) return;
679
694
  if (state.baselinePending) {
680
695
  if (!baselineUsageIsSettled(entries)) return;
@@ -694,11 +709,22 @@ function createNativeAutocompact(dependencies = {}) {
694
709
  const pass = state.checkpointQueue[0];
695
710
  if (!pass) return;
696
711
  state.pass = pass;
712
+ const checkpointEntries = [...await execution.session.entries({
713
+ type: "custom",
714
+ customType: PLAN_DOCUMENT_ENTRY,
715
+ limit: 1
716
+ })];
717
+ if (pass > 1) for await (const record of execution.session.entriesNewestFirst()) {
718
+ const entry = record;
719
+ if (!latestCheckpointArtifactEntry([entry])) continue;
720
+ checkpointEntries.push(entry);
721
+ break;
722
+ }
697
723
  const messages = await canonical(execution, entries);
698
724
  const steering = await contributionSnapshot(execution);
699
725
  if (!alive(version)) return;
700
726
  snapshot = messages;
701
- const previous = pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(entries)) : void 0;
727
+ const previous = pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(checkpointEntries)) : void 0;
702
728
  const requestId = createRequestId(execution.sessionId, state.cycle, pass, currentLeaf);
703
729
  state.phase = "checkpoint_pending";
704
730
  state.requestId = requestId;
@@ -724,7 +750,7 @@ function createNativeAutocompact(dependencies = {}) {
724
750
  return execution.textCompletion.summarize(reference, {
725
751
  messages: pass > 1 && delta ? delta : messages,
726
752
  instructions: checkpointInstructions(pass, {
727
- plan: latestPlanSnapshot(entries),
753
+ plan: latestPlanSnapshot(checkpointEntries),
728
754
  contextContributions: steering,
729
755
  readFiles: state.readFiles,
730
756
  modifiedFiles: state.modifiedFiles
@@ -781,7 +807,11 @@ function createNativeAutocompact(dependencies = {}) {
781
807
  context = execution;
782
808
  applied.clear();
783
809
  invalid.clear();
784
- const entries = await branch(execution);
810
+ const entries = await execution.session.entries({
811
+ type: "custom",
812
+ customType: STATE_CUSTOM_TYPE,
813
+ limit: 1
814
+ });
785
815
  if (!alive(version)) return;
786
816
  const entry = entries.findLast((item) => item.type === "custom" && item.customType === "po-autocompact-state");
787
817
  const data = entry?.type === "custom" && entry.data && typeof entry.data === "object" ? entry.data : void 0;
@@ -791,7 +821,8 @@ function createNativeAutocompact(dependencies = {}) {
791
821
  snapshot = validMessages(data?.nativeSnapshot) ? data.nativeSnapshot : void 0;
792
822
  previousSnapshot = validMessages(data?.nativePreviousSnapshot) ? data.nativePreviousSnapshot : void 0;
793
823
  if (state.phase === "checkpoint_ready" && state.requestId) {
794
- const artifacts = entries.slice(entry ? entries.indexOf(entry) + 1 : 0);
824
+ const history = await branch(execution);
825
+ const artifacts = history.slice(entry ? history.findIndex((item) => item.id === entry.id) + 1 : 0);
795
826
  const committed = artifacts.findLast((item) => {
796
827
  const message = item.type === "message" ? item.message : void 0;
797
828
  if (message?.role !== "custom" || message.customType !== "po-autocompact-context") return false;
@@ -880,7 +911,7 @@ function createNativeAutocompact(dependencies = {}) {
880
911
  const started = Date.now();
881
912
  try {
882
913
  const version = generation;
883
- const entries = await branch(execution);
914
+ const entries = await contextBranch(execution);
884
915
  if (!alive(version)) return;
885
916
  const projection = projectContextMessages(event.messages, entries);
886
917
  if (projection.invalidMarker) {
@@ -926,9 +957,11 @@ function createNativeAutocompact(dependencies = {}) {
926
957
  if (!active || event.status !== "completed" || typeof event.entryId !== "string" || event.entryId === lastNativeCompactionId) return;
927
958
  const observedGeneration = generation;
928
959
  return enqueue(async () => {
929
- const entries = await branch(execution);
930
- const compacted = entries.findLast((entry) => entry.type === "compaction");
931
- if (!alive(observedGeneration) || !compacted || compacted.id !== event.entryId || compacted.id === lastNativeCompactionId) return;
960
+ const compacted = (await execution.session.entries({
961
+ type: "compaction",
962
+ limit: 1
963
+ }))[0];
964
+ if (!alive(observedGeneration) || !compacted || compacted.type !== "compaction" || compacted.id !== event.entryId || compacted.id === lastNativeCompactionId) return;
932
965
  generation += 1;
933
966
  const version = generation;
934
967
  controller?.abort(/* @__PURE__ */ new Error("Native compaction superseded checkpoint."));
@@ -939,7 +972,12 @@ function createNativeAutocompact(dependencies = {}) {
939
972
  state.modifiedFiles = files.modifiedFiles;
940
973
  await execution.session.setLabel?.(compacted.id, `autocompact:c${state.cycle}:external`);
941
974
  if (!alive(version)) return;
942
- const runtimeAttributes = await runtimeState(execution, entries, version);
975
+ const plan = await execution.session.entries({
976
+ type: "custom",
977
+ customType: PLAN_DOCUMENT_ENTRY,
978
+ limit: 1
979
+ });
980
+ const runtimeAttributes = await runtimeState(execution, plan, version);
943
981
  if (!alive(version)) return;
944
982
  const nativeAttributes = attributes();
945
983
  resetCycle();
@@ -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 { createPoTelemetry, type PoTelemetry, type PoTelemetryOptions } 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(event: AutocompactEventName, error: unknown, attributes?: AutocompactEventAttributes): 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) => telemetry.recordError(event, error, attributes),\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/** 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 { FOOTER_ORDER, FOOTER_SOURCE, SLOW_CONTEXT_HOOK_MS, STATUS_KEY } 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 { mirrorCompactionHistory } from '../compactionHistory';\nimport {\n baselineUsageIsSettled,\n checkpointRequestDetails,\n checkpointSummaryFromEntry,\n contextDetailsFromUnknown,\n createInitialState,\n createRequestId,\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, attributes());\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 (execution: PoHeadlessExecutionContext, version: number, error: unknown, malformed = false) => {\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) =>\n Promise.resolve().then(() =>\n telemetry.recordError(\n malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed,\n failure,\n {\n ...eventAttributes,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS,\n },\n ),\n ),\n ),\n ]);\n };\n const branch = async (execution: PoHeadlessExecutionContext) =>\n (await execution.session.entries()) as unknown as CompactionPolicyEntry[];\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 branch(execution),\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 branch(execution);\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(entries)) : undefined;\n const { reference, thinking } = await summaryModel(execution, configuration);\n const instructions = checkpointInstructions(3, {\n plan: latestPlanSnapshot(entries),\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 (execution: PoHeadlessExecutionContext, version: number): 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);\n return false;\n }\n const entries = await branch(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(execution, version, new Error('Canonical checkpoint evidence changed; summary must be regenerated.'));\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 if (!execution.session.appendMessage) throw new Error('Checkpoint messages are unavailable.');\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 const id = await execution.session.appendMessage({\n type: CONTEXT_MESSAGE_TYPE,\n text: withCanonicalFileSections(decision.summary, files),\n display: false,\n details,\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 entries,\n version,\n execution.session.appendMessage.bind(execution.session),\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 const checkpointExecution = { ...execution, session: { ...execution.session, appendMessage } };\n if (await applyReady(checkpointExecution, version)) 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 const entries = await branch(execution);\n if (!alive(version) || !usage || usage.tokens === null) 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 const thresholds = effectiveThresholds(\n usage.contextWindow,\n state.baselineTokens,\n configuration.ratios,\n resolveModelTokenOverrides(execution.model, configuration.overrides),\n );\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 messages = await canonical(execution, entries);\n const steering = await contributionSnapshot(execution);\n if (!alive(version)) return;\n snapshot = messages;\n const previous = pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(entries)) : 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 const completion = telemetry\n .runInSpan('po_autocompact.checkpoint', requestAttributes, async () => {\n const { reference, thinking } = await summaryModel(execution, configuration);\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(entries),\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(execution, version, new Error('Summarization returned an empty checkpoint.'));\n return;\n }\n state.phase = 'checkpoint_ready';\n state.pendingCheckpoint = summary.trim();\n await persist(execution, version);\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) await fail(execution, version, error);\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);\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 entries = await branch(execution);\n if (!alive(version)) return;\n const entry = entries.findLast((item) => item.type === 'custom' && item.customType === STATE_CUSTOM_TYPE);\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 (state.phase === 'checkpoint_ready' && state.requestId) {\n const artifacts = entries.slice(entry ? entries.indexOf(entry) + 1 : 0);\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 branch(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 branch(execution);\n const compacted = entries.findLast((entry) => entry.type === 'compaction');\n if (\n !alive(observedGeneration) ||\n !compacted ||\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 runtimeAttributes = await runtimeState(execution, entries, 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 ??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AAG,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/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 { createPoTelemetry, type PoTelemetry, type PoTelemetryOptions } 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(event: AutocompactEventName, error: unknown, attributes?: AutocompactEventAttributes): 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) => telemetry.recordError(event, error, attributes),\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/** 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 { 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, attributes());\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 (execution: PoHeadlessExecutionContext, version: number, error: unknown, malformed = false) => {\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) =>\n Promise.resolve().then(() =>\n telemetry.recordError(\n malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed,\n failure,\n {\n ...eventAttributes,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS,\n },\n ),\n ),\n ),\n ]);\n };\n const branch = async (execution: PoHeadlessExecutionContext) =>\n (await execution.session.entries()) as unknown as CompactionPolicyEntry[];\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 branch(execution),\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 branch(execution);\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(entries)) : undefined;\n const { reference, thinking } = await summaryModel(execution, configuration);\n const instructions = checkpointInstructions(3, {\n plan: latestPlanSnapshot(entries),\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 (execution: PoHeadlessExecutionContext, version: number): 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);\n return false;\n }\n const entries = await branch(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(execution, version, new Error('Canonical checkpoint evidence changed; summary must be regenerated.'));\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 if (!execution.session.appendMessage) throw new Error('Checkpoint messages are unavailable.');\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 const id = await execution.session.appendMessage({\n type: CONTEXT_MESSAGE_TYPE,\n text: withCanonicalFileSections(decision.summary, files),\n display: false,\n details,\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 entries,\n version,\n execution.session.appendMessage.bind(execution.session),\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 const checkpointExecution = { ...execution, session: { ...execution.session, appendMessage } };\n if (await applyReady(checkpointExecution, version)) 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 const entries = await contextBranch(execution);\n if (!alive(version) || !usage || usage.tokens === null) 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 const thresholds = effectiveThresholds(\n usage.contextWindow,\n state.baselineTokens,\n configuration.ratios,\n resolveModelTokenOverrides(execution.model, configuration.overrides),\n );\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 // Snapshot metadata can precede the context boundary, but is needed only when a checkpoint starts.\n const checkpointEntries = [\n ...(await execution.session.entries({\n type: 'custom',\n customType: PLAN_DOCUMENT_ENTRY,\n limit: 1,\n })),\n ] as unknown as CompactionPolicyEntry[];\n if (pass > 1) {\n for await (const record of execution.session.entriesNewestFirst()) {\n const entry = record as unknown as CompactionPolicyEntry;\n if (!latestCheckpointArtifactEntry([entry])) continue;\n checkpointEntries.push(entry);\n break;\n }\n }\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 const completion = telemetry\n .runInSpan('po_autocompact.checkpoint', requestAttributes, async () => {\n const { reference, thinking } = await summaryModel(execution, configuration);\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(execution, version, new Error('Summarization returned an empty checkpoint.'));\n return;\n }\n state.phase = 'checkpoint_ready';\n state.pendingCheckpoint = summary.trim();\n await persist(execution, version);\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) await fail(execution, version, error);\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);\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 entries = (await execution.session.entries({\n type: 'custom',\n customType: STATE_CUSTOM_TYPE,\n limit: 1,\n })) as unknown as CompactionPolicyEntry[];\n if (!alive(version)) return;\n const entry = entries.findLast((item) => item.type === 'custom' && item.customType === STATE_CUSTOM_TYPE);\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 (state.phase === 'checkpoint_ready' && state.requestId) {\n const history = await branch(execution);\n const artifacts = history.slice(entry ? history.findIndex((item) => item.id === entry.id) + 1 : 0);\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":";;;;;;;;;;AAEA,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;AAsBA,SAAgB,2BAA2B,UAAuC,CAAC,GAAyB;CAC1G,MAAM,YAAyB,kBAAkB;EAC/C,aAAa;EACb,aAAa;EACb,KAAK,QAAQ;EACb,eAAe,QAAQ;EACvB,KAAK,QAAQ;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M;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.36",
3
+ "version": "0.0.0-alpha.38",
4
4
  "description": "Iterative context compaction and checkpoint summaries for Po headless agent sessions.",
5
5
  "keywords": [
6
6
  "ai",
@@ -56,14 +56,14 @@
56
56
  "access": "public"
57
57
  },
58
58
  "dependencies": {
59
- "@agimon-ai/po-artifact": "0.0.0-alpha.35",
60
- "@agimon-ai/po-config": "0.0.0-alpha.36",
61
- "@agimon-ai/po-core": "0.0.0-alpha.36",
59
+ "@agimon-ai/po-artifact": "0.0.0-alpha.37",
60
+ "@agimon-ai/po-config": "0.0.0-alpha.38",
61
+ "@agimon-ai/po-core": "0.0.0-alpha.38",
62
62
  "@deepseek-ai/cordis": "4.0.5",
63
63
  "minimatch": "10.2.6"
64
64
  },
65
65
  "devDependencies": {
66
- "@agimon-ai/po-build": "0.0.0-alpha.36",
66
+ "@agimon-ai/po-build": "0.0.0-alpha.38",
67
67
  "@earendil-works/pi-coding-agent": "1.3.0",
68
68
  "@types/node": "26.6.5",
69
69
  "@vitest/coverage-v8": "5.0.4",