@agimon-ai/po-autocompact 0.0.0-alpha.13 → 0.0.0-alpha.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,7 +19,7 @@ asynchronous checkpoints and combines each checkpoint with subsequent messages.
19
19
 
20
20
  `po init` include Autocompact in `default.packages` in `.po/modes.yaml`.
21
21
  Remove it or move it to a named layer to change which major modes load it.
22
- The native session facet is `@agimon-ai/po-autocompact/extensions/server`.
22
+ The native server plugin is `@agimon-ai/po-autocompact/extensions/server`.
23
23
  This package does not provide a Pi extension or terminal UI.
24
24
 
25
25
  ## Checkpoint ladder
@@ -87,7 +87,7 @@ import { thresholdTokens } from '@agimon-ai/po-autocompact';
87
87
  import type { AutocompactPass } from '@agimon-ai/po-autocompact';
88
88
  ```
89
89
 
90
- The server host mounts the native facet and owns its lifecycle. `thresholdTokens` exposes
90
+ The server host mounts the native server plugin and owns its lifecycle. `thresholdTokens` exposes
91
91
  the threshold policy for hosts that need to preview or test checkpoint boundaries.
92
92
 
93
93
  ## Development
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  //#region src/schemas/apiContracts.ts
6
- /** This facet contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
6
+ /** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
7
7
  const apiContracts = (0, require("@agimon-ai/po-core/apiContracts").defineApiContract)({
8
8
  version: 1,
9
9
  http: [],
@@ -1 +1 @@
1
- {"version":3,"file":"apiContracts.cjs","names":["defineApiContract"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\n\n/** This facet contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */\nexport const apiContracts = defineApiContract({ version: 1, http: [], sockets: [], dynamic: [] });\nexport default apiContracts;\n"],"mappings":";;;;;;AAGA,MAAa,gBAAA,4CAAeA,CAAAA,CAAAA,kBAAAA,CAAkB;CAAE,SAAS;CAAG,MAAM,CAAC;CAAG,SAAS,CAAC;CAAG,SAAS,CAAC;AAAE,CAAC"}
1
+ {"version":3,"file":"apiContracts.cjs","names":["defineApiContract"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\n\n/** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */\nexport const apiContracts = defineApiContract({ version: 1, http: [], sockets: [], dynamic: [] });\nexport default apiContracts;\n"],"mappings":";;;;;;AAGA,MAAa,gBAAA,4CAAeA,CAAAA,CAAAA,kBAAAA,CAAkB;CAAE,SAAS;CAAG,MAAM,CAAC;CAAG,SAAS,CAAC;CAAG,SAAS,CAAC;AAAE,CAAC"}
@@ -1,5 +1,5 @@
1
1
  //#region src/schemas/apiContracts.d.ts
2
- /** This facet contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
2
+ /** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
3
3
  export declare const apiContracts: {
4
4
  version: 1;
5
5
  protocols?: Record<string, string> | undefined;
@@ -1,6 +1,6 @@
1
1
  import { defineApiContract } from "@agimon-ai/po-core/apiContracts";
2
2
  //#region src/schemas/apiContracts.ts
3
- /** This facet contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
3
+ /** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
4
4
  const apiContracts = defineApiContract({
5
5
  version: 1,
6
6
  http: [],
@@ -1 +1 @@
1
- {"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\n\n/** This facet contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */\nexport const apiContracts = defineApiContract({ version: 1, http: [], sockets: [], dynamic: [] });\nexport default apiContracts;\n"],"mappings":";;;AAGA,MAAa,eAAe,kBAAkB;CAAE,SAAS;CAAG,MAAM,CAAC;CAAG,SAAS,CAAC;CAAG,SAAS,CAAC;AAAE,CAAC"}
1
+ {"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\n\n/** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */\nexport const apiContracts = defineApiContract({ version: 1, http: [], sockets: [], dynamic: [] });\nexport default apiContracts;\n"],"mappings":";;;AAGA,MAAa,eAAe,kBAAkB;CAAE,SAAS;CAAG,MAAM,CAAC;CAAG,SAAS,CAAC;CAAG,SAAS,CAAC;AAAE,CAAC"}
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_compactionPolicy = require("../compactionPolicy-BH0jiFUR.cjs");
6
- let _agimon_ai_po_core_serverFacet = require("@agimon-ai/po-core/serverFacet");
6
+ let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
7
7
  let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
8
8
  let _agimon_ai_po_core_contextContributions = require("@agimon-ai/po-core/contextContributions");
9
9
  let _agimon_ai_po_core_uiHub = require("@agimon-ai/po-core/uiHub");
@@ -819,11 +819,12 @@ const via = (identity, value) => value === void 0 ? void 0 : {
819
819
  ...identity,
820
820
  ...value
821
821
  };
822
- const facet = (0, _agimon_ai_po_core_serverFacet.defineServerPlugin)({
822
+ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
823
823
  name: "@agimon-ai/po-autocompact",
824
- providerOverrides: (0, _agimon_ai_po_core_serverFacet.composeServerProviderOverrides)(root_server_default),
824
+ providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default),
825
+ injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({ session: [root_server_default] }),
825
826
  session: async (context) => {
826
- const scopeSession = await root_server_default(context);
827
+ const scopeSession = await context.scopeRoot("session", root_server_default, context);
827
828
  const contextSession = {
828
829
  ...context,
829
830
  root: scopeSession.value
@@ -849,7 +850,7 @@ const facet = (0, _agimon_ai_po_core_serverFacet.defineServerPlugin)({
849
850
  }
850
851
  });
851
852
  //#endregion
852
- exports.default = facet;
853
- exports.facet = facet;
853
+ exports.default = serverPlugin;
854
+ exports.serverPlugin = serverPlugin;
854
855
 
855
856
  //# sourceMappingURL=server.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.cjs","names":["PO_CONTEXT_CONTRIBUTIONS_SERVICE","loadPoConfig","createPoTelemetry","createInitialState","STATE_CUSTOM_TYPE","projectContextMessages","RUNTIME_STATE_MESSAGE_TYPE","parseCheckpointDecision","isStructuredCheckpoint","CHECKPOINT_MESSAGE_TYPE","checkpointRequestDetails","mergeFileDetails","fileOperationsFromMessages","CONTEXT_MESSAGE_TYPE","withCanonicalFileSections","RESUME_MESSAGE_TYPE","baselineUsageIsSettled","effectiveThresholds","checkpointSummaryFromEntry","latestCheckpointArtifactEntry","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","composeRootHooks","hookAgentSettled","hookContext","hookSessionBeforeCompact","hookSessionCompact","hookSessionStart","hookSessionTree","hookTurnEnd"],"sources":["../../src/constants/runtime.ts","../../src/services/autocompactRuntime/index.ts","../../src/services/autocompactTelemetry/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":["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 { createPoTelemetry, type PoTelemetry, type PoTelemetryOptions } from '@agimon-ai/po-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} 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","/**\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 {\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 {\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 lastNativeCompactionId: string | undefined;\n let checkpointBoundary:\n | ReturnType<NonNullable<PoHeadlessExecutionContext['session']['registerCheckpointBoundary']>>\n | 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 nativeSnapshot: snapshot,\n nativePreviousSnapshot: previousSnapshot,\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 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 await persist(execution, version);\n if (!alive(version)) return;\n await execution.client.notify({\n body: `Po autocompact summarization pass ${pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n level: 'error',\n });\n await telemetry.recordError(\n malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed,\n error,\n {\n ...eventAttributes,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS,\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 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 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 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 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 progress = 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 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.pass = pass;\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 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 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 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 restore = async (execution: PoHeadlessExecutionContext) => {\n if (!active) return;\n if (!checkpointBoundary) {\n if (!execution.session.registerCheckpointBoundary)\n 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 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') {\n state.phase = 'waiting';\n clear();\n await persist(execution, version);\n }\n if (alive(version)) await enqueue(() => progress(execution));\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 active &&\n !navigating &&\n configured(execution).enabled &&\n event.reason === 'threshold' &&\n (state.phase === 'checkpoint_pending' || state.phase === 'checkpoint_ready' || state.baselinePending)\n ? { cancel: true }\n : undefined,\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 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';\n\nimport { createNativeAutocompact } from '../../../../services/nativeAutocompact';\n\nexport default defineRoot(() => {\n const runtime = createNativeAutocompact();\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/serverFacet';\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/serverFacet';\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/serverFacet';\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/serverFacet';\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/serverFacet';\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/serverFacet';\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/serverFacet';\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/serverFacet';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';\nimport { composeRootHooks } 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 facet = defineServerPlugin({\n name: '@agimon-ai/po-autocompact',\n providerOverrides: composeServerProviderOverrides(rootSession),\n session: async (context) => {\n const scopeSession = await 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 facet;\n"],"mappings":";;;;;;;;;;;;AAEA,MAAa,gBAAgB;AAE7B,MAAa,aAAa;;;AC2B1B,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,SAAgB,mBAAmB,QAAoE;CACrG,KAAK,MAAM,SAAS,OAAO,WAAW,GAAG;EACvC,IAAI,MAAM,SAAS,YAAY,MAAM,eAAA,+BAAoC;EACzE,IAAI,CAAC,MAAM,QAAQ,OAAO,MAAM,SAAS,UAAU,OAAO,KAAA;EAC1D,MAAM,OAAO,MAAM;EACnB,IAAI,OAAO,KAAK,YAAY,YAAY,OAAO,KAAK,SAAS,UAAU,OAAO,KAAA;EAC9E,OAAO;GAAE,SAAS,KAAK;GAAS,MAAM,KAAK;EAAK;CAClD;AAEF;AAEA,MAAM,8BAA8D,OAAO,OAAO;CAChF,SAAS,OAAO,OAAO,CAAC,CAAC;CACzB,QAAQ,OAAO,OAAO,CAAC,CAAC;AAC1B,CAAC;AAED,SAAgB,iCAC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C,+BAAAA,+BAAAA,CAA+BC,mBAAW;CAC7D,SAAS,OAAO,YAAY;EAC1B,MAAM,eAAe,MAAMA,oBAAY,OAAO;EAC9C,MAAM,iBAAiB;GAAE,GAAG;GAAS,MAAM,aAAa;EAAM;EAC9D,OAAO;GACL,IAAA,GAAGC,iCAAAA,iBAAAA,CAAiB,YAAY;GAChC,IAAI,QAAwC;IAAE,OAAO;KAAC,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,8BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,UAAU,GAAG,GAAGC,wBAAa,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,yBAAyB,GAAG,GAAGC,uCAA0B,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,kBAAkB,GAAG,GAAGC,gCAAoB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,8BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,eAAe,GAAG,GAAGC,6BAAiB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,WAAW,GAAG,GAAGC,yBAAa,cAAc,CAAC;IAAC;GAAG;GACtiB,UAAU,CAAC,GAAI,aAAa,YAAY,CAAC,CAAE;GAC3C,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EACvG;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"server.cjs","names":["PO_CONTEXT_CONTRIBUTIONS_SERVICE","loadPoConfig","createPoTelemetry","createInitialState","STATE_CUSTOM_TYPE","projectContextMessages","RUNTIME_STATE_MESSAGE_TYPE","parseCheckpointDecision","isStructuredCheckpoint","CHECKPOINT_MESSAGE_TYPE","checkpointRequestDetails","mergeFileDetails","fileOperationsFromMessages","CONTEXT_MESSAGE_TYPE","withCanonicalFileSections","RESUME_MESSAGE_TYPE","baselineUsageIsSettled","effectiveThresholds","checkpointSummaryFromEntry","latestCheckpointArtifactEntry","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/constants/runtime.ts","../../src/services/autocompactRuntime/index.ts","../../src/services/autocompactTelemetry/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":["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 { createPoTelemetry, type PoTelemetry, type PoTelemetryOptions } from '@agimon-ai/po-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} 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","/**\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 {\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 {\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 lastNativeCompactionId: string | undefined;\n let checkpointBoundary:\n | ReturnType<NonNullable<PoHeadlessExecutionContext['session']['registerCheckpointBoundary']>>\n | 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 nativeSnapshot: snapshot,\n nativePreviousSnapshot: previousSnapshot,\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 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 await persist(execution, version);\n if (!alive(version)) return;\n await execution.client.notify({\n body: `Po autocompact summarization pass ${pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n level: 'error',\n });\n await telemetry.recordError(\n malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed,\n error,\n {\n ...eventAttributes,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS,\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 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 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 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 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 progress = 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 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.pass = pass;\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 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 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 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 restore = async (execution: PoHeadlessExecutionContext) => {\n if (!active) return;\n if (!checkpointBoundary) {\n if (!execution.session.registerCheckpointBoundary)\n 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 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') {\n state.phase = 'waiting';\n clear();\n await persist(execution, version);\n }\n if (alive(version)) await enqueue(() => progress(execution));\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 active &&\n !navigating &&\n configured(execution).enabled &&\n event.reason === 'threshold' &&\n (state.phase === 'checkpoint_pending' || state.phase === 'checkpoint_ready' || state.baselinePending)\n ? { cancel: true }\n : undefined,\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 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';\n\nimport { createNativeAutocompact } from '../../../../services/nativeAutocompact';\n\nexport default defineRoot(() => {\n const runtime = createNativeAutocompact();\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,MAAa,gBAAgB;AA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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,5 +1,5 @@
1
1
  //#region generated/server.d.ts
2
- export declare const facet: import("@agimon-ai/po-core/serverFacet").PoServerFacet;
2
+ export declare const serverPlugin: import("@agimon-ai/po-core/serverPlugin").PoServerPlugin;
3
3
  //#endregion
4
- export { facet as default };
4
+ export { serverPlugin as default };
5
5
  //# sourceMappingURL=server.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../../generated/server.ts"],"mappings":";qBAoBa,gDAAK"}
1
+ {"version":3,"file":"server.d.mts","names":[],"sources":["../../generated/server.ts"],"mappings":";qBAoBa,wDAAY"}
@@ -1,6 +1,6 @@
1
1
  import { S as STATE_CUSTOM_TYPE, _ as withCanonicalFileSections, a as createInitialState, b as RESUME_MESSAGE_TYPE, c as fileDetailsFromUnknown, d as latestCheckpointArtifactEntry, f as mergeFileDetails, h as projectContextMessages, i as contextDetailsFromUnknown, l as fileOperationsFromMessages, m as parseState, n as checkpointRequestDetails, o as createRequestId, p as parseCheckpointDecision, r as checkpointSummaryFromEntry, s as effectiveThresholds, t as baselineUsageIsSettled, u as isStructuredCheckpoint, v as CHECKPOINT_MESSAGE_TYPE, x as RUNTIME_STATE_MESSAGE_TYPE, y as CONTEXT_MESSAGE_TYPE } from "../compactionPolicy-BwT6SX7k.mjs";
2
- import { composeServerProviderOverrides, defineServerPlugin } from "@agimon-ai/po-core/serverFacet";
3
- import { composeRootHooks, defineHook, defineRoot } from "@agimon-ai/po-core/extensionFile";
2
+ import { composeServerProviderOverrides, defineServerPlugin } from "@agimon-ai/po-core/serverPlugin";
3
+ import { composeRootHooks, composeRootInjects, defineHook, defineRoot } from "@agimon-ai/po-core/extensionFile";
4
4
  import { PO_CONTEXT_CONTRIBUTIONS_SERVICE, requirePoContextContributions } from "@agimon-ai/po-core/contextContributions";
5
5
  import { PO_UI_HUB_SERVICE, requirePoUiHub } from "@agimon-ai/po-core/uiHub";
6
6
  import { loadPoConfig } from "@agimon-ai/po-config";
@@ -815,11 +815,12 @@ const via = (identity, value) => value === void 0 ? void 0 : {
815
815
  ...identity,
816
816
  ...value
817
817
  };
818
- const facet = defineServerPlugin({
818
+ const serverPlugin = defineServerPlugin({
819
819
  name: "@agimon-ai/po-autocompact",
820
820
  providerOverrides: composeServerProviderOverrides(root_server_default),
821
+ injects: composeRootInjects({ session: [root_server_default] }),
821
822
  session: async (context) => {
822
- const scopeSession = await root_server_default(context);
823
+ const scopeSession = await context.scopeRoot("session", root_server_default, context);
823
824
  const contextSession = {
824
825
  ...context,
825
826
  root: scopeSession.value
@@ -845,6 +846,6 @@ const facet = defineServerPlugin({
845
846
  }
846
847
  });
847
848
  //#endregion
848
- export { facet as default, facet };
849
+ export { serverPlugin as default, serverPlugin };
849
850
 
850
851
  //# sourceMappingURL=server.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":["rootSession","hookAgentSettled","hookContext","hookSessionBeforeCompact","hookSessionCompact","hookSessionStart","hookSessionTree","hookTurnEnd"],"sources":["../../src/constants/runtime.ts","../../src/services/autocompactRuntime/index.ts","../../src/services/autocompactTelemetry/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":["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 { createPoTelemetry, type PoTelemetry, type PoTelemetryOptions } from '@agimon-ai/po-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} 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","/**\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 {\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 {\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 lastNativeCompactionId: string | undefined;\n let checkpointBoundary:\n | ReturnType<NonNullable<PoHeadlessExecutionContext['session']['registerCheckpointBoundary']>>\n | 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 nativeSnapshot: snapshot,\n nativePreviousSnapshot: previousSnapshot,\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 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 await persist(execution, version);\n if (!alive(version)) return;\n await execution.client.notify({\n body: `Po autocompact summarization pass ${pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n level: 'error',\n });\n await telemetry.recordError(\n malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed,\n error,\n {\n ...eventAttributes,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS,\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 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 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 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 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 progress = 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 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.pass = pass;\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 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 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 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 restore = async (execution: PoHeadlessExecutionContext) => {\n if (!active) return;\n if (!checkpointBoundary) {\n if (!execution.session.registerCheckpointBoundary)\n 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 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') {\n state.phase = 'waiting';\n clear();\n await persist(execution, version);\n }\n if (alive(version)) await enqueue(() => progress(execution));\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 active &&\n !navigating &&\n configured(execution).enabled &&\n event.reason === 'threshold' &&\n (state.phase === 'checkpoint_pending' || state.phase === 'checkpoint_ready' || state.baselinePending)\n ? { cancel: true }\n : undefined,\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 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';\n\nimport { createNativeAutocompact } from '../../../../services/nativeAutocompact';\n\nexport default defineRoot(() => {\n const runtime = createNativeAutocompact();\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/serverFacet';\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/serverFacet';\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/serverFacet';\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/serverFacet';\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/serverFacet';\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/serverFacet';\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/serverFacet';\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/serverFacet';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';\nimport { composeRootHooks } 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 facet = defineServerPlugin({\n name: '@agimon-ai/po-autocompact',\n providerOverrides: composeServerProviderOverrides(rootSession),\n session: async (context) => {\n const scopeSession = await 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 facet;\n"],"mappings":";;;;;;;;AAEA,MAAa,gBAAgB;AAE7B,MAAa,aAAa;;;AC2B1B,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,SAAgB,mBAAmB,QAAoE;CACrG,KAAK,MAAM,SAAS,OAAO,WAAW,GAAG;EACvC,IAAI,MAAM,SAAS,YAAY,MAAM,eAAA,+BAAoC;EACzE,IAAI,CAAC,MAAM,QAAQ,OAAO,MAAM,SAAS,UAAU,OAAO,KAAA;EAC1D,MAAM,OAAO,MAAM;EACnB,IAAI,OAAO,KAAK,YAAY,YAAY,OAAO,KAAK,SAAS,UAAU,OAAO,KAAA;EAC9E,OAAO;GAAE,SAAS,KAAK;GAAS,MAAM,KAAK;EAAK;CAClD;AAEF;AAEA,MAAM,8BAA8D,OAAO,OAAO;CAChF,SAAS,OAAO,OAAO,CAAC,CAAC;CACzB,QAAQ,OAAO,OAAO,CAAC,CAAC;AAC1B,CAAC;AAED,SAAgB,iCACd,SACgC;CAChC,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI;EACF,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;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/constants/runtime.ts","../../src/services/autocompactRuntime/index.ts","../../src/services/autocompactTelemetry/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":["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 { createPoTelemetry, type PoTelemetry, type PoTelemetryOptions } from '@agimon-ai/po-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} 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","/**\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 {\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 {\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 lastNativeCompactionId: string | undefined;\n let checkpointBoundary:\n | ReturnType<NonNullable<PoHeadlessExecutionContext['session']['registerCheckpointBoundary']>>\n | 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 nativeSnapshot: snapshot,\n nativePreviousSnapshot: previousSnapshot,\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 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 await persist(execution, version);\n if (!alive(version)) return;\n await execution.client.notify({\n body: `Po autocompact summarization pass ${pass} failed: ${error instanceof Error ? error.message : String(error)}`,\n level: 'error',\n });\n await telemetry.recordError(\n malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed,\n error,\n {\n ...eventAttributes,\n 'autocompact.checkpoint.attempts': attempts,\n 'autocompact.checkpoint.exhausted': attempts >= MAX_INVALID_CHECKPOINT_ATTEMPTS,\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 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 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 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 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 progress = 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 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.pass = pass;\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 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 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 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 restore = async (execution: PoHeadlessExecutionContext) => {\n if (!active) return;\n if (!checkpointBoundary) {\n if (!execution.session.registerCheckpointBoundary)\n 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 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') {\n state.phase = 'waiting';\n clear();\n await persist(execution, version);\n }\n if (alive(version)) await enqueue(() => progress(execution));\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 active &&\n !navigating &&\n configured(execution).enabled &&\n event.reason === 'threshold' &&\n (state.phase === 'checkpoint_pending' || state.phase === 'checkpoint_ready' || state.baselinePending)\n ? { cancel: true }\n : undefined,\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 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';\n\nimport { createNativeAutocompact } from '../../../../services/nativeAutocompact';\n\nexport default defineRoot(() => {\n const runtime = createNativeAutocompact();\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,MAAa,gBAAgB;AAE7B,MAAa,aAAa;;;AC2B1B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,CAACA,mBAAW,EAAE,CAAC;CACtD,SAAS,OAAO,YAAY;EAC1B,MAAM,eAAe,MAAM,QAAQ,UAAU,WAAWA,qBAAa,OAAO;EAC5E,MAAM,iBAAiB;GAAE,GAAG;GAAS,MAAM,aAAa;EAAM;EAC9D,OAAO;GACL,GAAG,iBAAiB,YAAY;GAChC,IAAI,QAAwC;IAAE,OAAO;KAAC,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,8BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,UAAU,GAAG,GAAGC,wBAAa,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,yBAAyB,GAAG,GAAGC,uCAA0B,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,kBAAkB,GAAG,GAAGC,gCAAoB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,gBAAgB,GAAG,GAAGC,8BAAkB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,eAAe,GAAG,GAAGC,6BAAiB,cAAc,CAAC;KAAG,IAAI,EAAE,OAAO,WAAW,GAAG,GAAGC,yBAAa,cAAc,CAAC;IAAC;GAAG;GACtiB,UAAU,CAAC,GAAI,aAAa,YAAY,CAAC,CAAE;GAC3C,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EACvG;CACF;AACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-autocompact",
3
- "version": "0.0.0-alpha.13",
3
+ "version": "0.0.0-alpha.15",
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-config": "0.0.0-alpha.13",
60
- "@agimon-ai/po-core": "0.0.0-alpha.13",
61
- "@agimon-ai/po-telemetry": "0.0.0-alpha.13",
62
- "@deepseek-ai/cordis": "4.0.4",
59
+ "@agimon-ai/po-config": "0.0.0-alpha.15",
60
+ "@agimon-ai/po-core": "0.0.0-alpha.15",
61
+ "@agimon-ai/po-telemetry": "0.0.0-alpha.15",
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.13",
66
+ "@agimon-ai/po-build": "0.0.0-alpha.15",
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",