@agimon-ai/po-cloudflare 0.0.2-alpha.11 → 0.0.2-alpha.13

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.
Files changed (94) hide show
  1. package/dist/agent-DYFqCLl2.js +6850 -0
  2. package/dist/assets/plugins/assets/base-C3j1WCCq.css +2 -0
  3. package/dist/assets/plugins/chunks/po-web-runtime-Czm_C4SJ.js +1 -0
  4. package/dist/assets/plugins/compositions.json +1 -1
  5. package/dist/assets/plugins/slots/approval.8b3f37d9-CqQk6XG_.js +2 -0
  6. package/dist/assets/plugins/slots/artifacts.47d00f81-D-vQ-7Iz.js +1 -0
  7. package/dist/assets/plugins/slots/autocompact.9a92993d-B3KTYwW1.js +1 -0
  8. package/dist/assets/plugins/slots/builtin-tools.939bbfff-CZRYQVIP.js +7 -0
  9. package/dist/assets/plugins/slots/codemode.782e5bb1-Bzl_K_vt.js +10 -0
  10. package/dist/assets/plugins/slots/domain.21790b66-CvnpuKCY.js +1 -0
  11. package/dist/assets/plugins/slots/edit.c7c85129-kaxIknZ-.js +7 -0
  12. package/dist/assets/plugins/slots/files.bbcef824-wuB8gcQA.js +2 -0
  13. package/dist/assets/plugins/slots/grep.3dfd3214-3FnU8p-d.js +1 -0
  14. package/dist/assets/plugins/slots/log.33bc7d38-C0PXQ0O1.js +4 -0
  15. package/dist/assets/plugins/slots/mcp.59c68bcb-D0CkHnIw.js +109 -0
  16. package/dist/assets/plugins/slots/{profile.ab16dcec-B5yt7eny.js → profile.ea55f5e1-BSY3iYfJ.js} +1 -1
  17. package/dist/assets/plugins/slots/prompts.9957cc84-xdCkNkoA.js +3 -0
  18. package/dist/assets/plugins/slots/read.30a617e7-qqaxVlEX.js +1 -0
  19. package/dist/assets/plugins/slots/runner.9f3559b0-DfO2Z9HG.js +8 -0
  20. package/dist/assets/plugins/slots/skill.f506a5ea-CL_n-l4h.js +4 -0
  21. package/dist/assets/plugins/slots/vault.01657352-DbG3F_on.js +1 -0
  22. package/dist/{atomicJson-C_lN9leA.js → atomicJson-BF1fVXy1.js} +1 -1
  23. package/dist/browser-BWf8OMfl.js +3 -0
  24. package/dist/childSession-Cf2-kH4O.js +22 -0
  25. package/dist/{server-D190dXDN.js → dist-B-vqs6tA.js} +1 -546
  26. package/dist/{domains-CPX1dEVa.js → domains-Bl6T2dKV.js} +2 -2
  27. package/dist/{server-C5wixba6.js → esm-BKJy3O9-.js} +3 -296
  28. package/dist/{exports-2Vv52b9v.js → exports-CxkWsXI9.js} +7 -6
  29. package/dist/{exports-BF12Ftrd.js → exports-DlcCEAe3.js} +2 -9
  30. package/dist/{extensionFile-DpVvh-ud.js → extensionFile-D7wk8tFr.js} +11 -1
  31. package/dist/harnessStore-Bap8lsAg.js +1 -0
  32. package/dist/{harnessStore-Ct329wxJ.js → harnessStore-flLz1I0F.js} +2 -2
  33. package/dist/help-DjybmnPW.js +91 -0
  34. package/dist/{hubChannel-kFgtfJnv.js → hubChannel-Bi3PQrfD.js} +3 -27
  35. package/dist/hubRevisions-58pU2dW5.js +363 -0
  36. package/dist/index.edge-C9_xuXyy.js +57 -0
  37. package/dist/{index.edge-DhV_hfZA.js → index.edge-CJ2TFpgF.js} +2 -2
  38. package/dist/index.edge-COJJ_Dv2.js +937 -0
  39. package/dist/index.edge-ChYa2LU4.js +14 -0
  40. package/dist/index.edge-ClLTmPFz.js +191 -0
  41. package/dist/{index.edge-BNElrrHY.js → index.edge-uSjRpm6Z.js} +5 -0
  42. package/dist/iso-BPQViXM8.js +10 -0
  43. package/dist/{layeredConfig-BhFC6TBD.js → layeredConfig-B4s0eZ5o.js} +11 -4
  44. package/dist/{majorModes-CZqrWarh.js → majorModes-IygGmbb8.js} +2 -2
  45. package/dist/majorModes-xpLK9HpD.js +1 -0
  46. package/dist/notification-bGq1frYG.js +99 -0
  47. package/dist/piConfig-CcoMX-1L.js +127 -0
  48. package/dist/{platformFiles-BTDsAsmT.js → platformFiles-Ccj9HCvA.js} +24 -2
  49. package/dist/pluginContributions-Be9EnCAW.js +16 -0
  50. package/dist/sealedChannel-BeWNTWys.js +27 -0
  51. package/dist/server-4CmqIbH2.js +1476 -0
  52. package/dist/{server-DesPQYzJ.js → server-5vLvBTTs.js} +1 -1
  53. package/dist/server-BHhb0oir.js +505 -0
  54. package/dist/server-Bm6pAAw8.js +935 -0
  55. package/dist/server-C82Qzoh3.js +2658 -0
  56. package/dist/server-C8HyW7wN.js +489 -0
  57. package/dist/{server-DSusAvqK.js → server-C9gff7gU.js} +1 -1
  58. package/dist/{server-CTIkoJXM.js → server-CIhwIcbA.js} +4 -4
  59. package/dist/{server-DbmCxFL-.js → server-CMaTba5B.js} +1 -1
  60. package/dist/{server-DolHpEoY.js → server-COE7BKSa.js} +1 -1
  61. package/dist/server-CQXqMpeC.js +1744 -0
  62. package/dist/{server-BG6gwBcv.js → server-CTSvwoDy.js} +5 -4
  63. package/dist/server-C_34VM3M.js +217 -0
  64. package/dist/{server-CuGXhVFA.js → server-C_3jK2WM.js} +5 -5
  65. package/dist/server-CcNMwEFQ.js +190 -0
  66. package/dist/{server-D-zQp04y.js → server-CjsKNdSN.js} +1 -1
  67. package/dist/{server-DQy8hVXg.js → server-ClsNJwdv.js} +8 -8
  68. package/dist/{server-DfBHHyQo.js → server-Co57A8MH.js} +2 -9
  69. package/dist/{server-CRtXiNBP.js → server-CpJNq249.js} +5 -5
  70. package/dist/{server-zYYAg7ki.js → server-CxGGQFJs.js} +5 -16
  71. package/dist/{server-DpVsUiA-.js → server-DSu_uLDX.js} +4 -4
  72. package/dist/server-DeSuziRK.js +680 -0
  73. package/dist/{server-BIjpcE0Y.js → server-ZsazKk-n.js} +3 -3
  74. package/dist/{server-CZoHLCxk.js → server-il_s2Ycz.js} +5 -93
  75. package/dist/server-ziNfBZ2M.js +295 -0
  76. package/dist/{sessionConfig-BLmM5XLM.js → sessionConfig-DzAs6Pt-.js} +64 -499
  77. package/dist/{notification-qvyJJ_Df.js → telemetry-Csv1ZxAn.js} +1 -99
  78. package/dist/truncate-M3KbFyVj.js +89 -0
  79. package/dist/web-Cfvbn9H1.js +3 -0
  80. package/dist/worker.js +4545 -12244
  81. package/dist/workflow-w5JPZXgc.js +23 -0
  82. package/package.json +32 -24
  83. package/dist/assets/plugins/assets/base-_m1hGahv.css +0 -2
  84. package/dist/assets/plugins/chunks/po-web-runtime-CGjOl_1I.js +0 -1
  85. package/dist/assets/plugins/slots/approval.09e72f36-BW92gZQg.js +0 -2
  86. package/dist/assets/plugins/slots/artifacts.50b639bb-B6zDJhex.js +0 -1
  87. package/dist/assets/plugins/slots/builtin-tools.75108f21-DS-dJ07p.js +0 -7
  88. package/dist/assets/plugins/slots/codemode.c58fb583--t-nrGeQ.js +0 -10
  89. package/dist/assets/plugins/slots/domain.753f9f92-DWSqP3Jw.js +0 -1
  90. package/dist/assets/plugins/slots/mcp.82cc1ff5-jPY2OCuu.js +0 -109
  91. package/dist/assets/plugins/slots/skill.62a0a1b3-GtWLT33O.js +0 -4
  92. package/dist/assets/plugins/slots/vault.3cbfcdc3-B7BKfR_H.js +0 -1
  93. package/dist/harnessStore-BDI-s999.js +0 -1
  94. package/dist/majorModes-CzAWXyaf.js +0 -1
@@ -0,0 +1,1476 @@
1
+ import { J as composeServerProviderOverrides } from "./serverPlugin-pCqlBqQG.js";
2
+ import { n as DEFAULT_COMPACTION_POLICY } from "./agent-DYFqCLl2.js";
3
+ import { i as defineHook, n as composeRootInjects, p as defineServerPlugin, s as defineRoot, t as composeRootHooks } from "./extensionFile-D7wk8tFr.js";
4
+ import { t as createPoTelemetry } from "./index.edge-ChYa2LU4.js";
5
+ import { a as readArtifactBytes, c as ArtifactAccessError, f as COMPACTION_ARTIFACT_DIRECTORY, i as openArtifact, l as artifactRoot, o as removeArtifact, r as listArtifacts, s as writeArtifactText } from "./index.edge-C9_xuXyy.js";
6
+ import { p as loadPoConfig } from "./sessionConfig-DzAs6Pt-.js";
7
+ import "./exports-CxkWsXI9.js";
8
+ import { t as minimatch } from "./esm-BKJy3O9-.js";
9
+ //#region ../../core/po-core/src/schemas/contextContributions.ts
10
+ /** Session-scoped broker for bounded context rendered by optional Po packages. */
11
+ const PO_CONTEXT_CONTRIBUTIONS_SERVICE = "po/context-contributions";
12
+ function readPoContextContributions(context) {
13
+ return context.get(PO_CONTEXT_CONTRIBUTIONS_SERVICE);
14
+ }
15
+ function requirePoContextContributions(context) {
16
+ const service = readPoContextContributions(context);
17
+ if (!service) throw new Error("Po context contributions are unavailable. Start a Po session first.");
18
+ return service;
19
+ }
20
+ //#endregion
21
+ //#region ../../default/po-autocompact/src/services/autocompactTelemetry/index.ts
22
+ const SERVICE_NAME = "po-autocompact";
23
+ const PACKAGE_NAME = "@agimon-ai/po-autocompact";
24
+ const AUTOCOMPACT_EVENT = {
25
+ checkpointStarted: "po_autocompact.checkpoint_started",
26
+ checkpointCompleted: "po_autocompact.checkpoint_completed",
27
+ checkpointFailed: "po_autocompact.checkpoint_failed",
28
+ checkpointInvalid: "po_autocompact.checkpoint_invalid",
29
+ configurationLoadFailed: "po_autocompact.configuration_load_failed",
30
+ contextContributionDegraded: "po_autocompact.context_contribution_degraded",
31
+ contextCommitted: "po_autocompact.context_committed",
32
+ contextApplied: "po_autocompact.context_applied",
33
+ contextMarkerInvalid: "po_autocompact.context_marker_invalid",
34
+ contextHookSlow: "po_autocompact.context_hook_slow",
35
+ nativeCompactionCompleted: "po_autocompact.native_compaction_completed",
36
+ historyWriteFailed: "po_autocompact.history_write_failed"
37
+ };
38
+ function createAutocompactTelemetry(options = {}) {
39
+ const telemetry = createPoTelemetry({
40
+ serviceName: SERVICE_NAME,
41
+ packageName: PACKAGE_NAME,
42
+ cwd: options.cwd,
43
+ workspaceRoot: options.workspaceRoot,
44
+ env: options.env,
45
+ telemetryFactory: options.telemetryFactory,
46
+ warn: options.warn,
47
+ enableLogs: true,
48
+ enableTraces: true
49
+ });
50
+ return {
51
+ recordError: (event, error, attributes, errorOptions) => telemetry.recordError(event, error, attributes, errorOptions),
52
+ recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),
53
+ recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),
54
+ runInSpan: (name, attributes, callback) => telemetry.runInSpan(name, attributes, callback),
55
+ flush: () => telemetry.flush(),
56
+ shutdown: () => telemetry.shutdown()
57
+ };
58
+ }
59
+ //#endregion
60
+ //#region ../../core/po-core/src/schemas/uiHub.ts
61
+ /** The application-scoped UI aggregation service owned by po-ui. */
62
+ const PO_UI_HUB_SERVICE = "po/ui-hub";
63
+ function readPoUiHub(context) {
64
+ return context.get(PO_UI_HUB_SERVICE);
65
+ }
66
+ function requirePoUiHub(context) {
67
+ const hub = readPoUiHub(context);
68
+ if (!hub) throw new Error("Po UI hub is unavailable. Load @agimon-ai/po-ui.");
69
+ return hub;
70
+ }
71
+ //#endregion
72
+ //#region ../../default/po-autocompact/src/constants/autocompact.ts
73
+ const STATE_CUSTOM_TYPE = "po-autocompact-state";
74
+ const CHECKPOINT_MESSAGE_TYPE = "po-autocompact-checkpoint";
75
+ const CONTEXT_MESSAGE_TYPE = "po-autocompact-context";
76
+ const RESUME_MESSAGE_TYPE = "po-autocompact-resume";
77
+ const RUNTIME_STATE_MESSAGE_TYPE = "po-autocompact-runtime-state";
78
+ const COMPACTION_THRESHOLDS = {
79
+ 1: {
80
+ ratio: .5,
81
+ capTokens: 2e5
82
+ },
83
+ 2: {
84
+ ratio: .75,
85
+ capTokens: 5e5
86
+ },
87
+ 3: {
88
+ ratio: .95,
89
+ capTokens: 8e5
90
+ }
91
+ };
92
+ const CHECKPOINT_HEADINGS = [
93
+ "## Goal",
94
+ "## Constraints & Preferences",
95
+ "## Progress",
96
+ "### Done",
97
+ "### In Progress",
98
+ "### Blocked",
99
+ "## Key Decisions",
100
+ "## Next Steps",
101
+ "## Critical Context"
102
+ ];
103
+ //#endregion
104
+ //#region ../../default/po-autocompact/src/constants/runtime.ts
105
+ const PLAN_DOCUMENT_ENTRY = "agent-harness-plan-document";
106
+ const FOOTER_SOURCE = "po-autocompact";
107
+ const STATUS_KEY = "po-autocompact";
108
+ //#endregion
109
+ //#region ../../default/po-autocompact/src/services/autocompactRuntime/index.ts
110
+ function errorMessage(error) {
111
+ return error instanceof Error ? error.message : String(error);
112
+ }
113
+ function latestPlanSnapshot(branch) {
114
+ for (const entry of branch.toReversed()) {
115
+ if (entry.type !== "custom" || entry.customType !== "agent-harness-plan-document") continue;
116
+ if (!entry.data || typeof entry.data !== "object") return void 0;
117
+ const data = entry.data;
118
+ if (typeof data.content !== "string" || typeof data.path !== "string") return void 0;
119
+ return {
120
+ content: data.content,
121
+ path: data.path
122
+ };
123
+ }
124
+ }
125
+ const EMPTY_CONTEXT_CONTRIBUTIONS = Object.freeze({
126
+ entries: Object.freeze([]),
127
+ errors: Object.freeze([])
128
+ });
129
+ function readContextContributionsSnapshot(service) {
130
+ if (!service) return EMPTY_CONTEXT_CONTRIBUTIONS;
131
+ try {
132
+ return service.snapshot();
133
+ } catch (error) {
134
+ return {
135
+ entries: [],
136
+ errors: [{
137
+ source: PO_CONTEXT_CONTRIBUTIONS_SERVICE,
138
+ id: "service-snapshot",
139
+ label: "Context contributions",
140
+ order: 0,
141
+ message: errorMessage(error)
142
+ }]
143
+ };
144
+ }
145
+ }
146
+ function formatContextContributions(snapshot) {
147
+ const sections = snapshot.entries.map((entry) => `### ${entry.label}\n${entry.text}`);
148
+ sections.push(...snapshot.errors.map((error) => `### ${error.label}\n(unavailable: ${error.message})`));
149
+ return sections.length > 0 ? sections.join("\n\n") : "(no registered context contributions)";
150
+ }
151
+ function runtimeStateSnapshot(branch, contextContributions) {
152
+ const plan = latestPlanSnapshot(branch);
153
+ return {
154
+ ...plan ? { planPath: plan.path } : {},
155
+ contributions: contextContributions.entries,
156
+ contributionErrors: contextContributions.errors
157
+ };
158
+ }
159
+ function formatRuntimeState(snapshot) {
160
+ return `<compaction-runtime-state>
161
+ Authoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.
162
+ <active-plan>
163
+ ${snapshot.planPath ? `Source: ${snapshot.planPath}\nExact plan content is restored separately by Po Plan.` : "(no active plan document)"}
164
+ </active-plan>
165
+ <context-contributions>
166
+ ${formatContextContributions({
167
+ entries: snapshot.contributions,
168
+ errors: snapshot.contributionErrors
169
+ })}
170
+ </context-contributions>
171
+ </compaction-runtime-state>`;
172
+ }
173
+ function steeringEnvelope(snapshot) {
174
+ const plan = snapshot.plan ? `Source: ${snapshot.plan.path}\n\n${snapshot.plan.content}` : "(no active plan document)";
175
+ const importantContext = [snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(", ")}` : void 0, snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(", ")}` : void 0].filter((value) => Boolean(value));
176
+ return `<compaction-steering priority="user,plan,context-contributions,important-context,recent-messages">
177
+ <user-prompt source="conversation">
178
+ Treat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.
179
+ </user-prompt>
180
+ <active-plan>
181
+ ${plan}
182
+ </active-plan>
183
+ <context-contributions>
184
+ ${formatContextContributions(snapshot.contextContributions)}
185
+ </context-contributions>
186
+ <important-context>
187
+ ${importantContext.length > 0 ? importantContext.join("\n") : "(none recorded outside the conversation)"}
188
+ </important-context>
189
+ </compaction-steering>`;
190
+ }
191
+ function checkpointInstructions(pass, steering) {
192
+ const decision = pass === 2 ? "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" : "";
193
+ return `Create Po autocompact checkpoint pass ${pass}.
194
+
195
+ ${steeringEnvelope(steering)}
196
+
197
+ Apply 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.
198
+
199
+ ${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.
200
+
201
+ ## Goal
202
+ ## Constraints & Preferences
203
+ ## Progress
204
+ ### Done
205
+ ### In Progress
206
+ ### Blocked
207
+ ## Key Decisions
208
+ ## Next Steps
209
+ ## Critical Context`;
210
+ }
211
+ const DEFAULT_RUNTIME_CONFIG = {
212
+ enabled: true,
213
+ ratios: {},
214
+ overrides: []
215
+ };
216
+ /**
217
+ * What the Po config says about this package.
218
+ *
219
+ * `modes.autocompact` is read first and `modes.planning.subagents` is the
220
+ * fallback, because summarization borrowed the planning subagent model before
221
+ * it had keys of its own and existing files still spell it that way.
222
+ */
223
+ function autocompactRuntimeConfig(root, onLoadFailure) {
224
+ let modes;
225
+ try {
226
+ modes = loadPoConfig(root).modes;
227
+ } catch (error) {
228
+ process.emitWarning("Po autocompact configuration could not be loaded; using the active session model instead.");
229
+ onLoadFailure?.(error);
230
+ return DEFAULT_RUNTIME_CONFIG;
231
+ }
232
+ const configured = modes?.autocompact;
233
+ const agent = (configured && (configured.model !== void 0 || configured.thinking !== void 0) ? {
234
+ ...configured.model ? { model: configured.model } : {},
235
+ ...configured.thinking ? { thinking: configured.thinking } : {}
236
+ } : void 0) ?? modes?.planning?.subagents;
237
+ const thresholds = configured?.thresholds;
238
+ return {
239
+ enabled: configured?.enabled ?? true,
240
+ ...agent ? { agent } : {},
241
+ ratios: {
242
+ ...thresholds?.pass1 === void 0 ? {} : { 1: thresholds.pass1 },
243
+ ...thresholds?.pass2 === void 0 ? {} : { 2: thresholds.pass2 },
244
+ ...thresholds?.pass3 === void 0 ? {} : { 3: thresholds.pass3 }
245
+ },
246
+ overrides: configured?.overrides ?? []
247
+ };
248
+ }
249
+ //#endregion
250
+ //#region ../../default/po-autocompact/src/services/compactionPolicy/index.ts
251
+ function customMessage(entry) {
252
+ if (entry.type === "custom_message") return entry;
253
+ if (entry.type === "message" && entry.message.role === "custom") return entry.message;
254
+ }
255
+ const SHOULD_COMPACT_PATTERN = /<shouldCompact>\s*(true|false)\s*<\/shouldCompact>/i;
256
+ const FILE_SECTION_PATTERN = /\n*<(?:read-files|modified-files)>[\s\S]*?<\/(?:read-files|modified-files)>/g;
257
+ function isRecord(value) {
258
+ return typeof value === "object" && value !== null;
259
+ }
260
+ function isStringArray(value) {
261
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
262
+ }
263
+ function isPass(value) {
264
+ return value === 1 || value === 2 || value === 3;
265
+ }
266
+ function assistantText(entry) {
267
+ if (entry.type !== "message" || entry.message.role !== "assistant") return void 0;
268
+ return entry.message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n").trim() || void 0;
269
+ }
270
+ function isAutocompactMessage(value) {
271
+ return isRecord(value) && typeof value.role === "string";
272
+ }
273
+ function contextDetailsFromUnknown(value) {
274
+ if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return void 0;
275
+ if (!Array.isArray(value.retainedMessages) || !value.retainedMessages.every(isAutocompactMessage)) return void 0;
276
+ if (!isRecord(value.poAutocompact)) return void 0;
277
+ const marker = value.poAutocompact;
278
+ if (marker.version !== 2 || marker.pass !== 2 && marker.pass !== 3 || typeof marker.cycle !== "number" || typeof marker.requestId !== "string" || typeof marker.snapshotLeafId !== "string" || typeof marker.tokensBefore !== "number") return void 0;
279
+ return {
280
+ readFiles: [...value.readFiles],
281
+ modifiedFiles: [...value.modifiedFiles],
282
+ retainedMessages: [...value.retainedMessages],
283
+ poAutocompact: {
284
+ version: 2,
285
+ cycle: marker.cycle,
286
+ pass: marker.pass,
287
+ requestId: marker.requestId,
288
+ snapshotLeafId: marker.snapshotLeafId,
289
+ tokensBefore: marker.tokensBefore
290
+ }
291
+ };
292
+ }
293
+ function createInitialState() {
294
+ return {
295
+ version: 2,
296
+ cycle: 1,
297
+ pass: 1,
298
+ phase: "waiting",
299
+ checkpointQueue: [],
300
+ exhaustedPasses: [],
301
+ invalidAttempts: 0,
302
+ baselineTokens: 0,
303
+ baselinePending: false,
304
+ readFiles: [],
305
+ modifiedFiles: []
306
+ };
307
+ }
308
+ /**
309
+ * The ratios each pass fires at, with configured values folded in.
310
+ *
311
+ * The ladder only works if it climbs, so a configured pass never sits below the
312
+ * one before it: a file that says pass 2 fires earlier than pass 1 gets pass 1's
313
+ * ratio for pass 2 rather than a pass that can never contribute.
314
+ */
315
+ function compactionRatios(configured = {}) {
316
+ let previous = 0;
317
+ const ratios = {};
318
+ for (const pass of [
319
+ 1,
320
+ 2,
321
+ 3
322
+ ]) {
323
+ const ratio = Math.max(configured[pass] ?? COMPACTION_THRESHOLDS[pass].ratio, previous);
324
+ ratios[pass] = ratio;
325
+ previous = ratio;
326
+ }
327
+ return ratios;
328
+ }
329
+ function thresholdTokens(pass, contextWindow, baselineTokens = 0, configured = {}) {
330
+ const threshold = COMPACTION_THRESHOLDS[pass];
331
+ const ratio = compactionRatios(configured)[pass];
332
+ const baseline = Math.max(0, Math.min(baselineTokens, contextWindow));
333
+ const remaining = contextWindow - baseline;
334
+ const staged = baseline + Math.min(Math.floor(remaining * ratio), threshold.capTokens);
335
+ const nativeTrigger = contextWindow - DEFAULT_COMPACTION_POLICY.reserveTokens;
336
+ return nativeTrigger > baseline ? Math.min(staged, nativeTrigger) : staged;
337
+ }
338
+ /**
339
+ * Where every pass fires, with a matching model's absolute token checkpoints folded in.
340
+ *
341
+ * A configured token count replaces the ratio only when it fires earlier, so an
342
+ * override can bring a checkpoint forward on a very large window without ever
343
+ * pushing one past the point Pi compacts natively.
344
+ *
345
+ * Two rules keep the ladder usable. A token count at or below the baseline is
346
+ * ignored, because a compaction that lands above it would otherwise satisfy that
347
+ * pass the moment the next cycle opens and re-fire it every turn. And a pass never
348
+ * sits below the one before it, for the same reason {@link compactionRatios}
349
+ * climbs: `evaluateUsage` skips any pass below the one already reached, so a later
350
+ * pass that fires first does not merely reorder the ladder, it locks the earlier
351
+ * passes out of the cycle and forces compaction with no summary ever written.
352
+ */
353
+ function effectiveThresholds(contextWindow, baselineTokens = 0, configured = {}, tokenOverrides = {}) {
354
+ let previous = 0;
355
+ const thresholds = {};
356
+ for (const pass of [
357
+ 1,
358
+ 2,
359
+ 3
360
+ ]) {
361
+ const ratioTokens = thresholdTokens(pass, contextWindow, baselineTokens, configured);
362
+ const absolute = tokenOverrides[pass];
363
+ thresholds[pass] = Math.max(absolute !== void 0 && absolute > baselineTokens ? Math.min(ratioTokens, absolute) : ratioTokens, previous);
364
+ previous = thresholds[pass];
365
+ }
366
+ return thresholds;
367
+ }
368
+ function latestCheckpointArtifactEntry(branchEntries) {
369
+ return branchEntries.findLast((entry) => entry.type === "compaction" || entry.type === "custom" && entry.customType === "po-autocompact-checkpoint" || customMessage(entry)?.customType === "po-autocompact-checkpoint" || customMessage(entry)?.customType === "po-autocompact-context");
370
+ }
371
+ function baselineUsageIsSettled(branchEntries) {
372
+ const boundaryIndex = branchEntries.findLastIndex((entry) => entry.type === "compaction" || customMessage(entry)?.customType === "po-autocompact-context");
373
+ return branchEntries.slice(boundaryIndex + 1).some((entry) => {
374
+ if (entry.type !== "message" || entry.message.role !== "assistant") return false;
375
+ const { stopReason, usage } = entry.message;
376
+ if (stopReason === "aborted" || stopReason === "error" || !usage) return false;
377
+ return (usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;
378
+ });
379
+ }
380
+ function projectContextMessages(messages, branchEntries) {
381
+ const nativeCompactionIndex = branchEntries.findLastIndex((entry) => entry.type === "compaction");
382
+ const markerEntry = branchEntries.slice(nativeCompactionIndex + 1).findLast((entry) => customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE);
383
+ const markerMessage = markerEntry && customMessage(markerEntry);
384
+ if (!markerEntry || !markerMessage) return {
385
+ messages,
386
+ retainedMessageCount: 0
387
+ };
388
+ const details = contextDetailsFromUnknown(markerMessage.details);
389
+ const summary = checkpointSummaryFromEntry(markerEntry);
390
+ if (!details || !summary) return {
391
+ messages,
392
+ invalidMarker: true,
393
+ retainedMessageCount: 0
394
+ };
395
+ const markerMessageIndex = messages.findLastIndex((message) => message.role === "custom" && message.customType === "po-autocompact-context" && contextDetailsFromUnknown(message.details)?.poAutocompact.requestId === details.poAutocompact.requestId);
396
+ if (markerMessageIndex === -1) return {
397
+ messages,
398
+ invalidMarker: true,
399
+ retainedMessageCount: 0
400
+ };
401
+ return {
402
+ messages: [
403
+ {
404
+ role: "compactionSummary",
405
+ summary,
406
+ tokensBefore: details.poAutocompact.tokensBefore,
407
+ timestamp: messages[markerMessageIndex]?.timestamp ?? Date.now()
408
+ },
409
+ ...details.retainedMessages,
410
+ ...messages.slice(markerMessageIndex + 1)
411
+ ],
412
+ marker: details.poAutocompact,
413
+ retainedMessageCount: details.retainedMessages.length
414
+ };
415
+ }
416
+ function fileOperationsFromMessages(messages) {
417
+ const fileOps = {
418
+ read: /* @__PURE__ */ new Set(),
419
+ written: /* @__PURE__ */ new Set(),
420
+ edited: /* @__PURE__ */ new Set()
421
+ };
422
+ for (const message of messages) {
423
+ if (message.role !== "assistant") continue;
424
+ for (const block of message.content) {
425
+ if (block.type !== "toolCall") continue;
426
+ const path = typeof block.arguments.path === "string" ? block.arguments.path : void 0;
427
+ if (!path) continue;
428
+ if (block.name === "read") fileOps.read.add(path);
429
+ else if (block.name === "write") fileOps.written.add(path);
430
+ else if (block.name === "edit") fileOps.edited.add(path);
431
+ }
432
+ }
433
+ return fileOps;
434
+ }
435
+ function parseState(value) {
436
+ if (!isRecord(value)) return void 0;
437
+ if (value.version !== 2 || typeof value.cycle !== "number" || !isPass(value.pass)) return void 0;
438
+ if (value.phase !== "waiting" && value.phase !== "checkpoint_pending" && value.phase !== "checkpoint_ready" && value.phase !== "compacting") return void 0;
439
+ const baselineTokens = value.baselineTokens ?? 0;
440
+ if (typeof baselineTokens !== "number" || baselineTokens < 0) return void 0;
441
+ const baselinePending = value.baselinePending ?? false;
442
+ if (typeof baselinePending !== "boolean") return void 0;
443
+ const checkpointQueue = value.checkpointQueue ?? [];
444
+ if (!Array.isArray(checkpointQueue) || !checkpointQueue.every(isPass) || checkpointQueue.some((pass, index) => index > 0 && pass <= checkpointQueue[index - 1])) return void 0;
445
+ const exhaustedPasses = value.exhaustedPasses ?? [];
446
+ if (!Array.isArray(exhaustedPasses) || !exhaustedPasses.every(isPass)) return void 0;
447
+ const invalidAttempts = value.invalidAttempts ?? 0;
448
+ if (typeof invalidAttempts !== "number" || invalidAttempts < 0) return void 0;
449
+ if (!isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return void 0;
450
+ if (value.requestId !== void 0 && typeof value.requestId !== "string") return void 0;
451
+ if (value.compactionPass !== void 0 && value.compactionPass !== 2 && value.compactionPass !== 3) return void 0;
452
+ if ("latestCheckpointEntryId" in value) return void 0;
453
+ if (value.latestCheckpointSnapshotLeafId !== void 0 && typeof value.latestCheckpointSnapshotLeafId !== "string") return void 0;
454
+ if (value.lastAttemptLeafId !== void 0 && typeof value.lastAttemptLeafId !== "string") return void 0;
455
+ if (value.snapshotLeafId !== void 0 && typeof value.snapshotLeafId !== "string") return void 0;
456
+ if (value.snapshotTokens !== void 0 && (typeof value.snapshotTokens !== "number" || value.snapshotTokens < 0)) return void 0;
457
+ if (value.pendingCheckpoint !== void 0 && typeof value.pendingCheckpoint !== "string") return void 0;
458
+ return {
459
+ version: 2,
460
+ cycle: value.cycle,
461
+ pass: value.pass,
462
+ phase: value.phase,
463
+ checkpointQueue: [...checkpointQueue],
464
+ exhaustedPasses: [...exhaustedPasses],
465
+ invalidAttempts,
466
+ baselineTokens,
467
+ baselinePending,
468
+ readFiles: [...value.readFiles],
469
+ modifiedFiles: [...value.modifiedFiles],
470
+ ...value.requestId ? { requestId: value.requestId } : {},
471
+ ...value.compactionPass ? { compactionPass: value.compactionPass } : {},
472
+ ...value.latestCheckpointSnapshotLeafId ? { latestCheckpointSnapshotLeafId: value.latestCheckpointSnapshotLeafId } : {},
473
+ ...value.lastAttemptLeafId ? { lastAttemptLeafId: value.lastAttemptLeafId } : {},
474
+ ...value.snapshotLeafId ? { snapshotLeafId: value.snapshotLeafId } : {},
475
+ ...value.snapshotTokens !== void 0 ? { snapshotTokens: value.snapshotTokens } : {},
476
+ ...value.pendingCheckpoint ? { pendingCheckpoint: value.pendingCheckpoint } : {}
477
+ };
478
+ }
479
+ function checkpointSummaryFromEntry(entry) {
480
+ if (!entry) return void 0;
481
+ if (entry.type === "compaction") return entry.summary.trim() || void 0;
482
+ if (entry.type === "custom") return isRecord(entry.data) && typeof entry.data.summary === "string" ? entry.data.summary.trim() || void 0 : void 0;
483
+ const marker = customMessage(entry);
484
+ if (marker) return (typeof marker.content === "string" ? marker.content : marker.content.filter((block) => block.type === "text").map((block) => block.text).join("\n")).trim() || void 0;
485
+ return assistantText(entry);
486
+ }
487
+ function parseCheckpointDecision(response) {
488
+ const match = response.match(SHOULD_COMPACT_PATTERN);
489
+ const summary = response.replace(SHOULD_COMPACT_PATTERN, "").trim();
490
+ if (!match) return { summary };
491
+ return {
492
+ summary,
493
+ shouldCompact: match[1]?.toLowerCase() === "true"
494
+ };
495
+ }
496
+ function isStructuredCheckpoint(summary) {
497
+ return CHECKPOINT_HEADINGS.every((heading) => summary.includes(heading));
498
+ }
499
+ function createRequestId(sessionId, cycle, pass, leafId) {
500
+ return `${sessionId}:${cycle}:${pass}:${leafId ?? "root"}`;
501
+ }
502
+ function checkpointRequestDetails(cycle, pass, requestId) {
503
+ return {
504
+ version: 2,
505
+ cycle,
506
+ pass,
507
+ requestId
508
+ };
509
+ }
510
+ function mergeFileDetails(current, fileOps, additional) {
511
+ const modified = /* @__PURE__ */ new Set([
512
+ ...current.modifiedFiles,
513
+ ...additional?.modifiedFiles ?? [],
514
+ ...fileOps ? [...fileOps.edited, ...fileOps.written] : []
515
+ ]);
516
+ const read = /* @__PURE__ */ new Set([
517
+ ...current.readFiles,
518
+ ...additional?.readFiles ?? [],
519
+ ...fileOps ? [...fileOps.read] : []
520
+ ]);
521
+ for (const path of modified) read.delete(path);
522
+ const recent = (paths) => [...paths].slice(-500).sort();
523
+ return {
524
+ readFiles: recent(read),
525
+ modifiedFiles: recent(modified)
526
+ };
527
+ }
528
+ function fileDetailsFromUnknown(value) {
529
+ if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return void 0;
530
+ return {
531
+ readFiles: value.readFiles,
532
+ modifiedFiles: value.modifiedFiles
533
+ };
534
+ }
535
+ function withCanonicalFileSections(summary, details) {
536
+ const sections = [];
537
+ if (details.readFiles.length > 0) sections.push(`<read-files>\n${details.readFiles.join("\n")}\n</read-files>`);
538
+ if (details.modifiedFiles.length > 0) sections.push(`<modified-files>\n${details.modifiedFiles.join("\n")}\n</modified-files>`);
539
+ const normalized = summary.replace(FILE_SECTION_PATTERN, "").trim();
540
+ return sections.length > 0 ? `${normalized}\n\n${sections.join("\n\n")}` : normalized;
541
+ }
542
+ //#endregion
543
+ //#region ../../default/po-autocompact/src/services/compactionHistory/index.ts
544
+ const FORMAT = "po-compaction/1";
545
+ const HEADER = `---\nformat: ${JSON.stringify(FORMAT)}\n`;
546
+ const HISTORY_PATH = new RegExp(`^${COMPACTION_ARTIFACT_DIRECTORY}/(?:epoch-\\d+/(?:summary|checkpoint-\\d+)|in-epoch/checkpoint-\\d+)\\.md$`);
547
+ const NATIVE_PREFIX = "The conversation history before this point was compacted into the following summary:\n\n<summary>\n";
548
+ const NATIVE_SUFFIX = "\n</summary>";
549
+ function historyFile(path, fields, body) {
550
+ const header = Object.entries({
551
+ format: FORMAT,
552
+ ...fields
553
+ }).flatMap(([key, value]) => value === void 0 ? [] : [`${key}: ${JSON.stringify(value)}`]);
554
+ return {
555
+ path: `${COMPACTION_ARTIFACT_DIRECTORY}/${path}`,
556
+ text: `---\n${header.join("\n")}\n---\n\n${body}\n`
557
+ };
558
+ }
559
+ function isoTime(value) {
560
+ const time = new Date(value);
561
+ return Number.isFinite(time.getTime()) ? time.toISOString() : void 0;
562
+ }
563
+ function passOf(value) {
564
+ if (typeof value !== "object" || value === null || !("pass" in value)) return void 0;
565
+ return value.pass === 1 || value.pass === 2 || value.pass === 3 ? value.pass : void 0;
566
+ }
567
+ function committedFields(entry) {
568
+ if (entry.type === "compaction") {
569
+ const summary = entry.summary.trim();
570
+ return {
571
+ body: summary.startsWith(NATIVE_PREFIX) && summary.endsWith(NATIVE_SUFFIX) ? summary.slice(96, -11).trim() : summary,
572
+ fields: {
573
+ source: "compact",
574
+ tokensBefore: entry.tokensBefore > 0 ? entry.tokensBefore : void 0
575
+ }
576
+ };
577
+ }
578
+ const marker = customMessage(entry);
579
+ const details = marker?.customType === "po-autocompact-context" ? contextDetailsFromUnknown(marker.details) : void 0;
580
+ if (!details) return void 0;
581
+ return {
582
+ body: checkpointSummaryFromEntry(entry) ?? "",
583
+ fields: {
584
+ source: "autocompact",
585
+ pass: details.poAutocompact.pass,
586
+ tokensBefore: details.poAutocompact.tokensBefore
587
+ }
588
+ };
589
+ }
590
+ /** The only entries `wantedHistory` reads, so mirrors can scan history without keeping the rest. */
591
+ function isHistoryEntry(entry) {
592
+ const type = customMessage(entry)?.customType;
593
+ return entry.type === "compaction" || entry.type === "custom" && entry.customType === "po-autocompact-checkpoint" || type === "po-autocompact-checkpoint" || type === "po-autocompact-context";
594
+ }
595
+ /** Number commits along the active branch so a rewind rewrites the same epoch folders. */
596
+ function wantedHistory(entries) {
597
+ const files = [];
598
+ let staged = [];
599
+ let epoch = 1;
600
+ const checkpoints = (folder) => staged.map(({ entry, summary, pass }, index) => historyFile(`${folder}/checkpoint-${index + 1}.md`, {
601
+ kind: "checkpoint",
602
+ epoch,
603
+ checkpoint: index + 1,
604
+ entryId: entry.id,
605
+ source: "autocompact",
606
+ pass,
607
+ timestamp: isoTime(entry.timestamp)
608
+ }, summary));
609
+ for (const entry of entries) {
610
+ const marker = customMessage(entry);
611
+ if (entry.type === "custom" && entry.customType === "po-autocompact-checkpoint" || marker?.customType === "po-autocompact-checkpoint") {
612
+ const summary = checkpointSummaryFromEntry(entry);
613
+ if (summary) staged.push({
614
+ entry,
615
+ summary,
616
+ pass: passOf(entry.type === "custom" ? entry.data : marker?.details)
617
+ });
618
+ continue;
619
+ }
620
+ const committed = committedFields(entry);
621
+ if (!committed) continue;
622
+ files.push(...checkpoints(`epoch-${epoch}`), historyFile(`epoch-${epoch}/summary.md`, {
623
+ kind: "summary",
624
+ epoch,
625
+ entryId: entry.id,
626
+ ...committed.fields,
627
+ timestamp: isoTime(entry.timestamp)
628
+ }, committed.body));
629
+ staged = [];
630
+ epoch += 1;
631
+ }
632
+ files.push(...checkpoints("in-epoch"));
633
+ return files;
634
+ }
635
+ async function ownedHistory(root, path) {
636
+ const file = await openArtifact(root, path).catch((error) => {
637
+ if (error instanceof ArtifactAccessError && error.status === 404) return void 0;
638
+ throw error;
639
+ });
640
+ if (!file) return false;
641
+ try {
642
+ const bytes = await readArtifactBytes(file.handle, Math.min(file.stat.size, HEADER.length));
643
+ return new TextDecoder().decode(bytes) === HEADER;
644
+ } finally {
645
+ await file.handle.close();
646
+ }
647
+ }
648
+ /** Mirror history into the session artifact folder. Pruning touches only files carrying this mirror's header. */
649
+ async function mirrorCompactionHistory(root, entries) {
650
+ const files = wantedHistory(entries);
651
+ if (files.length === 0) return;
652
+ for (const file of files) await writeArtifactText(root, file.path, file.text);
653
+ const listed = await listArtifacts(root);
654
+ if (listed.error) throw new Error(listed.error);
655
+ const wanted = new Set(files.map((file) => file.path));
656
+ const stale = listed.items.filter((item) => HISTORY_PATH.test(item.path) && !wanted.has(item.path));
657
+ for (const item of stale) if (await ownedHistory(root, item.path)) await removeArtifact(root, item.path);
658
+ for (const folder of new Set(stale.map((item) => item.path.slice(0, item.path.lastIndexOf("/"))))) await removeArtifact(root, folder);
659
+ }
660
+ //#endregion
661
+ //#region ../../default/po-autocompact/src/services/modelOverrides/index.ts
662
+ /**
663
+ * A pattern naming a provider is matched against `provider/id`, anything else
664
+ * against the bare id. `*` does not cross `/`, so a bare pattern tested against a
665
+ * qualified subject would never match and would read as a silently dead rule.
666
+ */
667
+ function matchesModelPattern(pattern, model) {
668
+ const subject = pattern.includes("/") ? `${model.provider}/${model.id}` : model.id;
669
+ return minimatch(subject, pattern, { nocase: true });
670
+ }
671
+ function resolveModelTokenOverrides(model, overrides) {
672
+ if (!model) return {};
673
+ const matched = overrides.find((entry) => matchesModelPattern(entry.model, model));
674
+ if (!matched) return {};
675
+ const { pass1, pass2, pass3 } = matched.tokens;
676
+ return {
677
+ ...pass1 === void 0 ? {} : { 1: pass1 },
678
+ ...pass2 === void 0 ? {} : { 2: pass2 },
679
+ ...pass3 === void 0 ? {} : { 3: pass3 }
680
+ };
681
+ }
682
+ //#endregion
683
+ //#region ../../default/po-autocompact/src/services/summarizationModel/index.ts
684
+ const THINKING_SUFFIX_PATTERN = /:(off|minimal|low|medium|high|xhigh|max)$/;
685
+ /** Splits a `provider/model` reference, tolerating the optional thinking suffix. */
686
+ function parseModelReference(reference) {
687
+ const trimmed = reference.trim();
688
+ const thinking = THINKING_SUFFIX_PATTERN.exec(trimmed)?.[1];
689
+ const identity = trimmed.replace(THINKING_SUFFIX_PATTERN, "");
690
+ const separator = identity.indexOf("/");
691
+ if (separator <= 0 || separator >= identity.length - 1) return void 0;
692
+ return {
693
+ provider: identity.slice(0, separator),
694
+ modelId: identity.slice(separator + 1),
695
+ ...thinking ? { thinking } : {}
696
+ };
697
+ }
698
+ //#endregion
699
+ //#region ../../default/po-autocompact/src/services/nativeAutocompact/index.ts
700
+ /** Exact canonical-prefix comparison refuses to apply summaries to edited or replaced evidence. */
701
+ function tailAfter(snapshot, current) {
702
+ if (snapshot.length > current.length || snapshot.some((message, index) => JSON.stringify(message) !== JSON.stringify(current[index]))) return void 0;
703
+ return current.slice(snapshot.length);
704
+ }
705
+ function leaf(entries) {
706
+ return entries.findLast((entry) => entry.type !== "custom" || entry.customType !== "po-autocompact-state" && entry.customType !== "po-autocompact-checkpoint")?.id ?? "root";
707
+ }
708
+ function createNativeAutocompact(dependencies = {}) {
709
+ const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();
710
+ let active = true;
711
+ let generation = 0;
712
+ let state = createInitialState();
713
+ let snapshot;
714
+ let previousSnapshot;
715
+ let context;
716
+ let contributions;
717
+ let controller;
718
+ let serial = Promise.resolve();
719
+ const work = /* @__PURE__ */ new Set();
720
+ const applied = /* @__PURE__ */ new Set();
721
+ const invalid = /* @__PURE__ */ new Set();
722
+ let configFailureReported = false;
723
+ let footer;
724
+ let navigating = false;
725
+ let degraded = false;
726
+ let lastNativeCompactionId;
727
+ let checkpointBoundary;
728
+ let mirrorQueued = false;
729
+ let historyWarnedSession;
730
+ const attributes = () => ({
731
+ "pi.session.id": context?.sessionId ?? "",
732
+ "autocompact.cycle": state.cycle,
733
+ "autocompact.pass": state.pass,
734
+ ...state.requestId ? { "autocompact.request.id": state.requestId } : {},
735
+ ...state.snapshotLeafId ? { "autocompact.snapshot_leaf_id": state.snapshotLeafId } : {},
736
+ ...state.snapshotTokens === void 0 ? {} : { "autocompact.tokens_before": state.snapshotTokens }
737
+ });
738
+ const configured = (execution) => autocompactRuntimeConfig(execution.repoRoot, (error) => {
739
+ if (!configFailureReported) {
740
+ configFailureReported = true;
741
+ telemetry.recordWarning(AUTOCOMPACT_EVENT.configurationLoadFailed, error, {
742
+ ...attributes(),
743
+ "failure.kind": "configuration"
744
+ });
745
+ }
746
+ });
747
+ const alive = (version) => active && !navigating && generation === version;
748
+ const refreshStatus = (execution) => {
749
+ const phase = state.phase === "checkpoint_pending" ? "summarizing" : state.phase === "checkpoint_ready" ? "applying" : void 0;
750
+ footer?.update(phase ? {
751
+ fullText: `Compacting p${state.pass}`,
752
+ compactText: `C${state.pass}`
753
+ } : void 0);
754
+ execution.client.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : void 0);
755
+ };
756
+ const enqueue = (callback) => {
757
+ const version = generation;
758
+ const operation = serial.then(async () => {
759
+ if (alive(version)) await callback();
760
+ });
761
+ serial = operation.catch(() => void 0);
762
+ return operation;
763
+ };
764
+ const persist = async (execution, version) => {
765
+ if (!alive(version)) return;
766
+ await execution.session.appendCustomEntry(STATE_CUSTOM_TYPE, {
767
+ ...state,
768
+ nativeLastCompactionId: lastNativeCompactionId
769
+ });
770
+ if (alive(version)) refreshStatus(execution);
771
+ };
772
+ const clear = () => {
773
+ delete state.requestId;
774
+ delete state.snapshotLeafId;
775
+ delete state.snapshotTokens;
776
+ delete state.pendingCheckpoint;
777
+ delete state.compactionPass;
778
+ snapshot = void 0;
779
+ };
780
+ const fail = async (execution, version, error, malformed = false, kind = "unknown") => {
781
+ if (!alive(version)) return;
782
+ degraded = true;
783
+ const eventAttributes = attributes();
784
+ const attempts = state.invalidAttempts + 1;
785
+ const pass = state.pass;
786
+ const failedLeaf = state.snapshotLeafId;
787
+ state.invalidAttempts += 1;
788
+ if (state.invalidAttempts >= 3) {
789
+ state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);
790
+ state.exhaustedPasses.push(pass);
791
+ state.invalidAttempts = 0;
792
+ }
793
+ state.phase = "waiting";
794
+ clear();
795
+ state.lastAttemptLeafId = failedLeaf;
796
+ const errors = [error];
797
+ try {
798
+ await persist(execution, version);
799
+ } catch (persistError) {
800
+ errors.push(persistError);
801
+ }
802
+ if (!alive(version)) return;
803
+ await Promise.allSettled([Promise.resolve().then(() => execution.client.notify({
804
+ body: `Po autocompact summarization pass ${pass} failed: ${error instanceof Error ? error.message : String(error)}`,
805
+ level: "error"
806
+ })), ...errors.map((failure, index) => Promise.resolve().then(() => telemetry.recordError(malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed, failure, {
807
+ ...eventAttributes,
808
+ "failure.kind": index === 0 ? kind : "persistence",
809
+ "autocompact.checkpoint.attempts": attempts,
810
+ "autocompact.checkpoint.exhausted": attempts >= 3
811
+ }, { includeException: true })))]);
812
+ };
813
+ const matching = async (execution, keep, stopAt) => {
814
+ const entries = [];
815
+ for await (const record of execution.session.entriesNewestFirst()) {
816
+ const entry = record;
817
+ if (entry.id === stopAt) break;
818
+ if (keep(entry)) entries.push(entry);
819
+ }
820
+ return entries.reverse();
821
+ };
822
+ const policyEntries = async (execution, withCheckpoint) => {
823
+ const entries = [...await execution.session.entries({
824
+ type: "custom",
825
+ customType: PLAN_DOCUMENT_ENTRY,
826
+ limit: 1
827
+ })];
828
+ if (withCheckpoint) for await (const record of execution.session.entriesNewestFirst()) {
829
+ const entry = record;
830
+ if (!latestCheckpointArtifactEntry([entry])) continue;
831
+ entries.push(entry);
832
+ break;
833
+ }
834
+ return entries;
835
+ };
836
+ const contextBranch = async (execution) => {
837
+ const entries = [];
838
+ let foundLeaf = false;
839
+ for await (const record of execution.session.entriesNewestFirst()) {
840
+ const entry = record;
841
+ const isLeaf = leaf([entry]) !== "root";
842
+ if (entry.type !== "custom" || !foundLeaf && isLeaf) entries.push(entry);
843
+ if (isLeaf) foundLeaf = true;
844
+ if (entry.type === "compaction" || customMessage(entry)?.customType === "po-autocompact-context") break;
845
+ }
846
+ return entries.reverse();
847
+ };
848
+ const canonical = async (execution, entries) => {
849
+ if (!execution.session.contextMessages) throw new Error("Canonical context is unavailable for autocompact.");
850
+ return projectContextMessages(await execution.session.contextMessages(), entries).messages;
851
+ };
852
+ const scheduleMirror = (execution) => {
853
+ if (mirrorQueued) return;
854
+ mirrorQueued = true;
855
+ enqueue(async () => {
856
+ mirrorQueued = false;
857
+ try {
858
+ await mirrorCompactionHistory(artifactRoot(execution.sessionId, execution.environment), await matching(execution, isHistoryEntry));
859
+ } catch (error) {
860
+ const warn = historyWarnedSession !== execution.sessionId;
861
+ historyWarnedSession = execution.sessionId;
862
+ await Promise.allSettled([Promise.resolve().then(() => telemetry.recordWarning(AUTOCOMPACT_EVENT.historyWriteFailed, error, attributes())), ...warn ? [Promise.resolve().then(() => execution.client.notify({
863
+ body: `Po autocompact could not save compaction history: ${error instanceof Error ? error.message : String(error)}`,
864
+ level: "warning"
865
+ }))] : []]);
866
+ }
867
+ }).finally(() => {
868
+ mirrorQueued = false;
869
+ });
870
+ };
871
+ const contributionSnapshot = async (execution) => {
872
+ const result = readContextContributionsSnapshot(contributions);
873
+ for (const error of result.errors) {
874
+ await execution.client.notify({
875
+ body: `Po autocompact context contribution degraded (${error.source}/${error.id}): ${error.message}`,
876
+ level: "warning"
877
+ });
878
+ await telemetry.recordWarning(AUTOCOMPACT_EVENT.contextContributionDegraded, new Error(error.message), {
879
+ ...attributes(),
880
+ "autocompact.context_contribution.source": error.source,
881
+ "autocompact.context_contribution.id": error.id,
882
+ "autocompact.context_contribution.order": error.order
883
+ });
884
+ }
885
+ return result;
886
+ };
887
+ const runtimeState = async (execution, entries, version, appendMessage = checkpointBoundary?.appendMessage.bind(checkpointBoundary)) => {
888
+ const saved = runtimeStateSnapshot(entries, await contributionSnapshot(execution));
889
+ if (!alive(version)) return;
890
+ await appendMessage?.({
891
+ type: RUNTIME_STATE_MESSAGE_TYPE,
892
+ text: formatRuntimeState(saved),
893
+ display: false,
894
+ details: {
895
+ version: 2,
896
+ ...saved
897
+ }
898
+ });
899
+ return {
900
+ "autocompact.runtime.plan_present": Boolean(saved.planPath),
901
+ "autocompact.runtime.contribution_count": saved.contributions.length,
902
+ "autocompact.runtime.contribution_error_count": saved.contributionErrors.length
903
+ };
904
+ };
905
+ const summaryModel = async (execution, configuration) => {
906
+ const ownReference = configuration.agent?.model ? parseModelReference(configuration.agent.model) : void 0;
907
+ const candidate = ownReference ? `${ownReference.provider}/${ownReference.modelId}` : void 0;
908
+ const reference = candidate && execution.textCompletion.available(candidate) ? candidate : execution.model ? `${execution.model.provider}/${execution.model.id}` : "";
909
+ return {
910
+ reference,
911
+ thinking: configuration.agent?.thinking ?? (reference === candidate ? ownReference?.thinking : void 0) ?? (await execution.session.readModelSettings?.())?.thinkingLevel
912
+ };
913
+ };
914
+ const manualCompaction = async (event, execution) => {
915
+ const configuration = configured(execution);
916
+ if (!configuration.enabled || !execution.textCompletion?.summarize) return;
917
+ try {
918
+ const entries = await contextBranch(execution);
919
+ const pinned = await policyEntries(execution, state.pass > 1);
920
+ const messages = await canonical(execution, entries);
921
+ const delta = state.pass > 1 && previousSnapshot ? tailAfter(previousSnapshot, messages) : void 0;
922
+ const previous = state.pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(pinned)) : void 0;
923
+ const { reference, thinking } = await summaryModel(execution, configuration);
924
+ const instructions = checkpointInstructions(3, {
925
+ plan: latestPlanSnapshot(pinned),
926
+ contextContributions: await contributionSnapshot(execution),
927
+ readFiles: state.readFiles,
928
+ modifiedFiles: state.modifiedFiles
929
+ });
930
+ const { summary } = parseCheckpointDecision(await execution.textCompletion.summarize(reference, {
931
+ messages: delta ?? messages,
932
+ instructions: typeof event.instructions === "string" && event.instructions.trim() ? `${instructions}\n\n${event.instructions}` : instructions,
933
+ ...previous ? { previousSummary: previous } : {},
934
+ ...thinking ? { thinkingLevel: thinking } : {},
935
+ ...execution.signal ? { signal: execution.signal } : {}
936
+ }));
937
+ if (!isStructuredCheckpoint(summary)) throw new Error("Summarization returned an incomplete checkpoint.");
938
+ const files = mergeFileDetails(state, fileOperationsFromMessages(messages));
939
+ const usage = await execution.session.contextUsage?.();
940
+ return { compaction: {
941
+ summary: withCanonicalFileSections(summary, files),
942
+ tokensBefore: usage?.tokens ?? 0,
943
+ retainedTail: [],
944
+ details: files
945
+ } };
946
+ } catch (error) {
947
+ await execution.client.notify({
948
+ body: `Po autocompact manual compaction failed: ${error instanceof Error ? error.message : String(error)}`,
949
+ level: "error"
950
+ });
951
+ throw error;
952
+ }
953
+ };
954
+ const resetCycle = () => {
955
+ state.phase = "waiting";
956
+ state.checkpointQueue = [];
957
+ state.exhaustedPasses = [];
958
+ state.invalidAttempts = 0;
959
+ state.baselinePending = true;
960
+ state.cycle += 1;
961
+ state.pass = 1;
962
+ delete state.lastAttemptLeafId;
963
+ delete state.latestCheckpointSnapshotLeafId;
964
+ clear();
965
+ previousSnapshot = void 0;
966
+ };
967
+ const applyReady = async (execution, version, appendMessage) => {
968
+ if (state.phase !== "checkpoint_ready" || !state.pendingCheckpoint || !state.requestId || !state.snapshotLeafId) return false;
969
+ const decision = parseCheckpointDecision(state.pendingCheckpoint);
970
+ if (!isStructuredCheckpoint(decision.summary)) {
971
+ await fail(execution, version, /* @__PURE__ */ new Error("Summarization returned an incomplete checkpoint."), true, "validation");
972
+ return false;
973
+ }
974
+ const entries = await contextBranch(execution);
975
+ const messages = await canonical(execution, entries);
976
+ if (!alive(version)) return false;
977
+ const tail = snapshot && tailAfter(snapshot, messages);
978
+ if (!tail) {
979
+ await fail(execution, version, /* @__PURE__ */ new Error("Canonical checkpoint evidence changed; summary must be regenerated."), false, "evidence_changed");
980
+ return false;
981
+ }
982
+ const pass = state.pass;
983
+ if (pass === 1 || pass === 2 && decision.shouldCompact !== true) {
984
+ await execution.session.appendCustomEntry(CHECKPOINT_MESSAGE_TYPE, {
985
+ ...checkpointRequestDetails(state.cycle, pass, state.requestId),
986
+ summary: decision.summary
987
+ });
988
+ if (!alive(version)) return false;
989
+ previousSnapshot = snapshot;
990
+ state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;
991
+ state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);
992
+ state.pass = pass === 1 ? 2 : 3;
993
+ state.phase = "waiting";
994
+ state.invalidAttempts = 0;
995
+ clear();
996
+ await persist(execution, version);
997
+ scheduleMirror(execution);
998
+ return false;
999
+ }
1000
+ const files = mergeFileDetails(state, fileOperationsFromMessages(messages));
1001
+ const details = {
1002
+ ...files,
1003
+ poAutocompact: {
1004
+ version: 2,
1005
+ cycle: state.cycle,
1006
+ pass,
1007
+ requestId: state.requestId,
1008
+ snapshotLeafId: state.snapshotLeafId,
1009
+ tokensBefore: state.snapshotTokens ?? 0
1010
+ },
1011
+ retainedMessages: tail
1012
+ };
1013
+ const idle = (await execution.session.activity()).isIdle;
1014
+ if (!alive(version)) return false;
1015
+ const id = await appendMessage({
1016
+ type: CONTEXT_MESSAGE_TYPE,
1017
+ text: withCanonicalFileSections(decision.summary, files),
1018
+ display: false,
1019
+ details
1020
+ }, { resetContext: { retainedMessages: tail } });
1021
+ if (!alive(version) || !id) return false;
1022
+ await execution.session.setLabel?.(id, `autocompact:c${state.cycle}:p${pass}`);
1023
+ if (!alive(version)) return false;
1024
+ const runtimeAttributes = await runtimeState(execution, await policyEntries(execution, false), version, appendMessage);
1025
+ if (!alive(version)) return false;
1026
+ const committedAttributes = attributes();
1027
+ state.readFiles = files.readFiles;
1028
+ state.modifiedFiles = files.modifiedFiles;
1029
+ resetCycle();
1030
+ await persist(execution, version);
1031
+ scheduleMirror(execution);
1032
+ if (!alive(version)) return false;
1033
+ await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextCommitted, {
1034
+ ...committedAttributes,
1035
+ "autocompact.message_count.before": messages.length,
1036
+ "autocompact.message_count.retained": tail.length,
1037
+ "autocompact.apply_mode": idle ? "idle" : "turn_end",
1038
+ ...runtimeAttributes
1039
+ });
1040
+ if (idle && alive(version)) await execution.session.admitPrompt?.("Asynchronous compaction completed. Continue from the compacted checkpoint's immediate next action without repeating completed work.", "steer", void 0, `${RESUME_MESSAGE_TYPE}:${details.poAutocompact.requestId}`);
1041
+ return true;
1042
+ };
1043
+ const ensureCheckpointBoundary = (execution) => {
1044
+ if (checkpointBoundary) return;
1045
+ if (!execution.session.registerCheckpointBoundary) throw new Error("Native checkpoint boundaries are unavailable.");
1046
+ checkpointBoundary = execution.session.registerCheckpointBoundary(async (boundary) => {
1047
+ if (!active || navigating || boundary.signal?.aborted) return;
1048
+ const current = context ?? execution;
1049
+ await enqueue(() => boundary.signal?.aborted ? Promise.resolve() : progress(current, true, boundary.appendMessage.bind(boundary)));
1050
+ });
1051
+ };
1052
+ const advance = async (execution, allowBusy = false, appendMessage = checkpointBoundary?.appendMessage.bind(checkpointBoundary)) => {
1053
+ const version = generation;
1054
+ context = execution;
1055
+ const activity = await execution.session.activity();
1056
+ if (!alive(version) || activity.hasPendingMessages) return;
1057
+ if (appendMessage && (activity.isIdle || allowBusy)) {
1058
+ if (await applyReady(execution, version, appendMessage)) return;
1059
+ }
1060
+ if (!alive(version) || state.phase !== "waiting") return;
1061
+ const configuration = configured(execution);
1062
+ if (!configuration.enabled || !execution.session.contextUsage || !execution.textCompletion?.summarize) return;
1063
+ const usage = await execution.session.contextUsage();
1064
+ if (!alive(version) || !usage || typeof usage.tokens !== "number" || !Number.isFinite(usage.tokens) || usage.tokens < 0) return;
1065
+ const tokens = usage.tokens;
1066
+ const thresholds = effectiveThresholds(usage.contextWindow, state.baselineTokens, configuration.ratios, resolveModelTokenOverrides(execution.model, configuration.overrides));
1067
+ if (!state.baselinePending && !state.checkpointQueue.length && ![
1068
+ 1,
1069
+ 2,
1070
+ 3
1071
+ ].some((pass) => pass >= state.pass && !state.exhaustedPasses.includes(pass) && tokens >= thresholds[pass])) return;
1072
+ const entries = await contextBranch(execution);
1073
+ if (!alive(version)) return;
1074
+ if (state.baselinePending) {
1075
+ if (!baselineUsageIsSettled(entries)) return;
1076
+ state.baselineTokens = usage.tokens;
1077
+ state.baselinePending = false;
1078
+ await persist(execution, version);
1079
+ return;
1080
+ }
1081
+ const currentLeaf = leaf(entries);
1082
+ if (currentLeaf === state.lastAttemptLeafId) return;
1083
+ for (const pass of [
1084
+ 1,
1085
+ 2,
1086
+ 3
1087
+ ]) if (pass >= state.pass && !state.checkpointQueue.includes(pass) && !state.exhaustedPasses.includes(pass) && usage.tokens >= thresholds[pass]) state.checkpointQueue.push(pass);
1088
+ const pass = state.checkpointQueue[0];
1089
+ if (!pass) return;
1090
+ state.pass = pass;
1091
+ const checkpointEntries = await policyEntries(execution, pass > 1);
1092
+ const messages = await canonical(execution, entries);
1093
+ const steering = await contributionSnapshot(execution);
1094
+ if (!alive(version)) return;
1095
+ snapshot = messages;
1096
+ const previous = pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(checkpointEntries)) : void 0;
1097
+ const requestId = createRequestId(execution.sessionId, state.cycle, pass, currentLeaf);
1098
+ state.phase = "checkpoint_pending";
1099
+ state.requestId = requestId;
1100
+ state.snapshotLeafId = currentLeaf;
1101
+ state.snapshotTokens = usage.tokens;
1102
+ delete state.lastAttemptLeafId;
1103
+ delete state.pendingCheckpoint;
1104
+ await persist(execution, version);
1105
+ if (!alive(version)) return;
1106
+ degraded = false;
1107
+ controller?.abort();
1108
+ controller = new AbortController();
1109
+ const signal = controller.signal;
1110
+ const requestAttributes = {
1111
+ ...attributes(),
1112
+ "autocompact.message_count.before": messages.length
1113
+ };
1114
+ const delta = previousSnapshot ? tailAfter(previousSnapshot, messages) : void 0;
1115
+ let failureKind = "configuration";
1116
+ const completion = telemetry.runInSpan("po_autocompact.checkpoint", requestAttributes, async () => {
1117
+ const { reference, thinking } = await summaryModel(execution, configuration);
1118
+ failureKind = "unknown";
1119
+ if (!alive(version) || signal.aborted) return "";
1120
+ await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, requestAttributes);
1121
+ return execution.textCompletion.summarize(reference, {
1122
+ messages: pass > 1 && delta ? delta : messages,
1123
+ instructions: checkpointInstructions(pass, {
1124
+ plan: latestPlanSnapshot(checkpointEntries),
1125
+ contextContributions: steering,
1126
+ readFiles: state.readFiles,
1127
+ modifiedFiles: state.modifiedFiles
1128
+ }),
1129
+ ...previous ? { previousSummary: previous } : {},
1130
+ ...thinking ? { thinkingLevel: thinking } : {},
1131
+ signal
1132
+ });
1133
+ }).then(async (summary) => {
1134
+ await enqueue(async () => {
1135
+ if (!alive(version) || signal.aborted || state.requestId !== requestId) return;
1136
+ if (!summary.trim()) {
1137
+ await fail(execution, version, /* @__PURE__ */ new Error("Summarization returned an empty checkpoint."), false, "empty_checkpoint");
1138
+ return;
1139
+ }
1140
+ state.phase = "checkpoint_ready";
1141
+ state.pendingCheckpoint = summary.trim();
1142
+ failureKind = "persistence";
1143
+ await persist(execution, version);
1144
+ failureKind = "unknown";
1145
+ if (!alive(version)) return;
1146
+ await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {
1147
+ ...requestAttributes,
1148
+ "autocompact.checkpoint.characters": summary.length
1149
+ });
1150
+ if ((await execution.session.activity()).isIdle && alive(version)) await progress(execution);
1151
+ });
1152
+ }).catch(async (error) => {
1153
+ await enqueue(async () => {
1154
+ if (alive(version) && state.requestId === requestId) await fail(execution, version, error, false, failureKind);
1155
+ });
1156
+ });
1157
+ work.add(completion);
1158
+ completion.then(() => work.delete(completion), () => work.delete(completion));
1159
+ };
1160
+ const progress = async (execution, allowBusy = false, appendMessage) => {
1161
+ const version = generation;
1162
+ try {
1163
+ ensureCheckpointBoundary(execution);
1164
+ await advance(execution, allowBusy, appendMessage);
1165
+ } catch (error) {
1166
+ try {
1167
+ await fail(execution, version, error, false, "persistence");
1168
+ } finally {
1169
+ if (alive(version)) delete state.lastAttemptLeafId;
1170
+ }
1171
+ }
1172
+ };
1173
+ const load = async (execution) => {
1174
+ if (!active) return;
1175
+ navigating = false;
1176
+ generation += 1;
1177
+ const version = generation;
1178
+ controller?.abort(/* @__PURE__ */ new Error("Autocompact session generation changed."));
1179
+ controller = void 0;
1180
+ context = execution;
1181
+ applied.clear();
1182
+ invalid.clear();
1183
+ const saved = await execution.session.customSnapshot?.(STATE_CUSTOM_TYPE);
1184
+ if (!alive(version)) return;
1185
+ const entry = saved?.available ? saved.entry : void 0;
1186
+ const data = entry?.type === "custom" && entry.data && typeof entry.data === "object" ? entry.data : void 0;
1187
+ state = parseState(data) ?? createInitialState();
1188
+ lastNativeCompactionId = typeof data?.nativeLastCompactionId === "string" ? data.nativeLastCompactionId : void 0;
1189
+ const validMessages = (value) => Array.isArray(value) && value.every((message) => message && typeof message === "object" && typeof message.role === "string");
1190
+ snapshot = validMessages(data?.nativeSnapshot) ? data.nativeSnapshot : void 0;
1191
+ previousSnapshot = validMessages(data?.nativePreviousSnapshot) ? data.nativePreviousSnapshot : void 0;
1192
+ if (entry?.id && state.phase === "checkpoint_ready" && state.requestId) {
1193
+ const artifacts = await matching(execution, (item) => item.type === "custom" && item.customType === "po-autocompact-checkpoint" || customMessage(item)?.customType === "po-autocompact-context", entry?.id);
1194
+ const committed = artifacts.findLast((item) => {
1195
+ const message = item.type === "message" ? item.message : void 0;
1196
+ if (message?.role !== "custom" || message.customType !== "po-autocompact-context") return false;
1197
+ const details = contextDetailsFromUnknown(message.details);
1198
+ return details !== void 0 && details.poAutocompact.requestId === state.requestId && details.poAutocompact.cycle === state.cycle && details.poAutocompact.pass === state.pass && details.poAutocompact.snapshotLeafId === state.snapshotLeafId && isStructuredCheckpoint(checkpointSummaryFromEntry(item) ?? "");
1199
+ });
1200
+ if (committed?.type === "message" && committed.message.role === "custom") {
1201
+ const details = contextDetailsFromUnknown(committed.message.details);
1202
+ state.readFiles = details.readFiles;
1203
+ state.modifiedFiles = details.modifiedFiles;
1204
+ resetCycle();
1205
+ await persist(execution, version);
1206
+ } else if (artifacts.findLast((item) => {
1207
+ if (item.type !== "custom" || item.customType !== "po-autocompact-checkpoint") return false;
1208
+ const details = item.data;
1209
+ return details?.version === 2 && details.requestId === state.requestId && details.cycle === state.cycle && details.pass === state.pass && isStructuredCheckpoint(checkpointSummaryFromEntry(item) ?? "");
1210
+ }) && (state.pass === 1 || state.pass === 2)) {
1211
+ previousSnapshot = snapshot;
1212
+ state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;
1213
+ state.checkpointQueue = state.checkpointQueue.filter((pass) => pass !== state.pass);
1214
+ state.pass = state.pass === 1 ? 2 : 3;
1215
+ state.phase = "waiting";
1216
+ state.invalidAttempts = 0;
1217
+ clear();
1218
+ await persist(execution, version);
1219
+ }
1220
+ }
1221
+ if (state.phase !== "waiting" && (state.phase !== "checkpoint_ready" || !snapshot)) {
1222
+ state.phase = "waiting";
1223
+ clear();
1224
+ delete state.lastAttemptLeafId;
1225
+ await persist(execution, version);
1226
+ }
1227
+ if (!alive(version)) return;
1228
+ const progressed = enqueue(() => progress(execution));
1229
+ scheduleMirror(execution);
1230
+ await progressed;
1231
+ };
1232
+ const restore = async (execution) => {
1233
+ const version = generation + 1;
1234
+ try {
1235
+ await load(execution);
1236
+ } catch (error) {
1237
+ await fail(execution, version, error);
1238
+ }
1239
+ };
1240
+ return {
1241
+ hooks: [
1242
+ {
1243
+ event: "session_start",
1244
+ handle: (_event, execution) => restore(execution)
1245
+ },
1246
+ {
1247
+ event: "session_tree",
1248
+ handle: (event, execution) => {
1249
+ if (!active) return;
1250
+ if (event.status === "started") {
1251
+ navigating = true;
1252
+ generation += 1;
1253
+ controller?.abort(/* @__PURE__ */ new Error("Autocompact navigation started."));
1254
+ return;
1255
+ }
1256
+ return restore(execution);
1257
+ }
1258
+ },
1259
+ {
1260
+ event: "turn_end",
1261
+ handle: (_event, execution) => enqueue(() => progress(execution))
1262
+ },
1263
+ {
1264
+ event: "agent_settled",
1265
+ handle: (_event, execution) => enqueue(() => progress(execution))
1266
+ },
1267
+ {
1268
+ event: "session_before_compact",
1269
+ handle: (event, execution) => {
1270
+ if (!active || navigating) return;
1271
+ if (event.reason === "manual") return manualCompaction(event, execution);
1272
+ return !degraded && configured(execution).enabled && event.reason === "threshold" && (state.phase === "checkpoint_pending" || state.phase === "checkpoint_ready") ? { cancel: true } : void 0;
1273
+ }
1274
+ },
1275
+ {
1276
+ event: "context",
1277
+ async handle(event, execution) {
1278
+ if (!active || navigating || !Array.isArray(event.messages)) return;
1279
+ const started = Date.now();
1280
+ try {
1281
+ const version = generation;
1282
+ const entries = await contextBranch(execution);
1283
+ if (!alive(version)) return;
1284
+ const projection = projectContextMessages(event.messages, entries);
1285
+ if (projection.invalidMarker) {
1286
+ const id = leaf(entries);
1287
+ if (!invalid.has(id)) {
1288
+ invalid.add(id);
1289
+ await telemetry.recordError(AUTOCOMPACT_EVENT.contextMarkerInvalid, /* @__PURE__ */ new Error("Po autocompact context marker is malformed."), {
1290
+ ...attributes(),
1291
+ "autocompact.leaf_id": id
1292
+ });
1293
+ }
1294
+ return;
1295
+ }
1296
+ if (!projection.marker) return;
1297
+ if (!applied.has(projection.marker.requestId)) {
1298
+ applied.add(projection.marker.requestId);
1299
+ await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextApplied, {
1300
+ ...attributes(),
1301
+ "autocompact.request.id": projection.marker.requestId,
1302
+ "autocompact.cycle": projection.marker.cycle,
1303
+ "autocompact.pass": projection.marker.pass,
1304
+ "autocompact.snapshot_leaf_id": projection.marker.snapshotLeafId,
1305
+ "autocompact.tokens_before": projection.marker.tokensBefore,
1306
+ "autocompact.message_count.before": event.messages.length,
1307
+ "autocompact.message_count.after": projection.messages.length,
1308
+ "autocompact.message_count.retained": projection.retainedMessageCount
1309
+ });
1310
+ }
1311
+ return alive(version) ? { messages: projection.messages } : void 0;
1312
+ } finally {
1313
+ const hookMs = Date.now() - started;
1314
+ if (active && hookMs >= 25) await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextHookSlow, {
1315
+ ...attributes(),
1316
+ hook_ms: hookMs,
1317
+ "autocompact.message_count": event.messages.length
1318
+ });
1319
+ }
1320
+ }
1321
+ },
1322
+ {
1323
+ event: "session_compact",
1324
+ handle: (event, execution) => {
1325
+ if (!active || event.status !== "completed" || typeof event.entryId !== "string" || event.entryId === lastNativeCompactionId) return;
1326
+ const observedGeneration = generation;
1327
+ return enqueue(async () => {
1328
+ const compacted = (await execution.session.entries({
1329
+ type: "compaction",
1330
+ limit: 1
1331
+ }))[0];
1332
+ if (!alive(observedGeneration) || !compacted || compacted.type !== "compaction" || compacted.id !== event.entryId || compacted.id === lastNativeCompactionId) return;
1333
+ generation += 1;
1334
+ const version = generation;
1335
+ controller?.abort(/* @__PURE__ */ new Error("Native compaction superseded checkpoint."));
1336
+ controller = void 0;
1337
+ lastNativeCompactionId = compacted.id;
1338
+ const files = mergeFileDetails(state, void 0, fileDetailsFromUnknown("details" in compacted ? compacted.details : void 0));
1339
+ state.readFiles = files.readFiles;
1340
+ state.modifiedFiles = files.modifiedFiles;
1341
+ await execution.session.setLabel?.(compacted.id, `autocompact:c${state.cycle}:external`);
1342
+ if (!alive(version)) return;
1343
+ const plan = await execution.session.entries({
1344
+ type: "custom",
1345
+ customType: PLAN_DOCUMENT_ENTRY,
1346
+ limit: 1
1347
+ });
1348
+ const runtimeAttributes = await runtimeState(execution, plan, version);
1349
+ if (!alive(version)) return;
1350
+ const nativeAttributes = attributes();
1351
+ resetCycle();
1352
+ await persist(execution, version);
1353
+ scheduleMirror(execution);
1354
+ if (alive(version)) await telemetry.recordEvent(AUTOCOMPACT_EVENT.nativeCompactionCompleted, {
1355
+ ...nativeAttributes,
1356
+ "autocompact.native.reason": typeof event.reason === "string" ? event.reason : "unknown",
1357
+ "autocompact.native.from_extension": "fromHook" in compacted && compacted.fromHook === true,
1358
+ "autocompact.tokens_before": compacted.tokensBefore,
1359
+ ...runtimeAttributes
1360
+ });
1361
+ });
1362
+ }
1363
+ }
1364
+ ],
1365
+ plugin(cordis) {
1366
+ cordis.inject([PO_UI_HUB_SERVICE], (injected) => {
1367
+ const contribution = requirePoUiHub(injected).registerFooter({
1368
+ source: FOOTER_SOURCE,
1369
+ id: "autocompact",
1370
+ order: 20
1371
+ });
1372
+ footer = contribution;
1373
+ if (context && active) refreshStatus(context);
1374
+ return () => {
1375
+ contribution.dispose();
1376
+ if (footer === contribution) footer = void 0;
1377
+ };
1378
+ });
1379
+ cordis.inject([PO_CONTEXT_CONTRIBUTIONS_SERVICE], (injected) => {
1380
+ const service = requirePoContextContributions(injected);
1381
+ contributions = service;
1382
+ return () => {
1383
+ if (contributions === service) contributions = void 0;
1384
+ };
1385
+ });
1386
+ },
1387
+ start: restore,
1388
+ async stop() {
1389
+ active = false;
1390
+ checkpointBoundary?.dispose();
1391
+ checkpointBoundary = void 0;
1392
+ generation += 1;
1393
+ controller?.abort(/* @__PURE__ */ new Error("Autocompact is shutting down."));
1394
+ await Promise.allSettled([...work, serial]);
1395
+ context?.client.setStatus(STATUS_KEY, void 0);
1396
+ footer?.update(void 0);
1397
+ footer = void 0;
1398
+ context = void 0;
1399
+ contributions = void 0;
1400
+ await telemetry.shutdown();
1401
+ }
1402
+ };
1403
+ }
1404
+ //#endregion
1405
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/root.server.ts
1406
+ var root_server_default = defineRoot(({ agent }) => {
1407
+ const runtime = createNativeAutocompact({ telemetry: createAutocompactTelemetry({
1408
+ env: agent?.context.environment,
1409
+ cwd: agent?.context.cwd
1410
+ }) });
1411
+ return {
1412
+ value: runtime,
1413
+ services: [runtime.plugin],
1414
+ onDispose: runtime.stop
1415
+ };
1416
+ });
1417
+ //#endregion
1418
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
1419
+ var agent_settled_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "agent_settled"));
1420
+ //#endregion
1421
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/context.server.ts
1422
+ var context_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "context"));
1423
+ //#endregion
1424
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/session-before-compact.server.ts
1425
+ var session_before_compact_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "session_before_compact"));
1426
+ //#endregion
1427
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/session-compact.server.ts
1428
+ var session_compact_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "session_compact"));
1429
+ //#endregion
1430
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/session-start.server.ts
1431
+ var session_start_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "session_start"));
1432
+ //#endregion
1433
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/session-tree.server.ts
1434
+ var session_tree_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "session_tree"));
1435
+ //#endregion
1436
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/turn-end.server.ts
1437
+ var turn_end_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "turn_end"));
1438
+ //#endregion
1439
+ //#region ../../default/po-autocompact/generated/server.ts
1440
+ const at = (value, context) => typeof value === "function" ? value(context) : value;
1441
+ const via = (identity, value) => value === void 0 ? void 0 : {
1442
+ ...identity,
1443
+ ...value
1444
+ };
1445
+ const serverPlugin = defineServerPlugin({
1446
+ name: "@agimon-ai/po-autocompact",
1447
+ providerOverrides: composeServerProviderOverrides(root_server_default),
1448
+ injects: composeRootInjects({ session: [root_server_default] }),
1449
+ session: async (context) => {
1450
+ const scopeSession = await context.scopeRoot("session", root_server_default, context);
1451
+ const contextSession = {
1452
+ ...context,
1453
+ root: scopeSession.value
1454
+ };
1455
+ return {
1456
+ ...composeRootHooks(scopeSession),
1457
+ get hooks() {
1458
+ return [
1459
+ via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)),
1460
+ via({ event: "context" }, at(context_server_default, contextSession)),
1461
+ via({ event: "session_before_compact" }, at(session_before_compact_server_default, contextSession)),
1462
+ via({ event: "session_compact" }, at(session_compact_server_default, contextSession)),
1463
+ via({ event: "session_start" }, at(session_start_server_default, contextSession)),
1464
+ via({ event: "session_tree" }, at(session_tree_server_default, contextSession)),
1465
+ via({ event: "turn_end" }, at(turn_end_server_default, contextSession))
1466
+ ];
1467
+ },
1468
+ services: [...scopeSession.services ?? []],
1469
+ get activities() {
1470
+ return [...scopeSession.activities ?? []];
1471
+ }
1472
+ };
1473
+ }
1474
+ });
1475
+ //#endregion
1476
+ export { serverPlugin as default, serverPlugin };