@bastani/atomic 0.9.65 → 0.9.66

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 (48) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/package.json +1 -1
  5. package/dist/builtin/web-access/package.json +1 -1
  6. package/dist/builtin/workflows/package.json +1 -1
  7. package/dist/builtin/workflows/src/extension/index.bundle.mjs +154 -36
  8. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +125 -16
  9. package/dist/builtin/workflows/src/index.js +125 -16
  10. package/dist/builtin/workflows/src/local-worker-entry.mjs +125 -16
  11. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +8 -0
  12. package/dist/core/agent-session-auto-compaction.js +2 -2
  13. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  14. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  15. package/dist/core/agent-session-compaction.js +9 -1
  16. package/dist/core/agent-session-compaction.js.map +1 -1
  17. package/dist/core/agent-session-methods.d.ts +5 -2
  18. package/dist/core/agent-session-methods.d.ts.map +1 -1
  19. package/dist/core/agent-session-methods.js.map +1 -1
  20. package/dist/core/agent-session-post-tool-compaction.js +2 -2
  21. package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
  22. package/dist/core/compaction/compaction-runner.d.ts +18 -2
  23. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  24. package/dist/core/compaction/compaction-runner.js +129 -15
  25. package/dist/core/compaction/compaction-runner.js.map +1 -1
  26. package/dist/core/compaction/compaction-types.d.ts +4 -0
  27. package/dist/core/compaction/compaction-types.d.ts.map +1 -1
  28. package/dist/core/compaction/compaction-types.js.map +1 -1
  29. package/dist/core/settings-defaults.d.ts +2 -0
  30. package/dist/core/settings-defaults.d.ts.map +1 -1
  31. package/dist/core/settings-defaults.js +2 -0
  32. package/dist/core/settings-defaults.js.map +1 -1
  33. package/dist/core/settings-manager-basic-accessors.d.ts +2 -0
  34. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  35. package/dist/core/settings-manager-basic-accessors.js +7 -0
  36. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  37. package/dist/core/settings-schema.d.ts +2 -0
  38. package/dist/core/settings-schema.d.ts.map +1 -1
  39. package/dist/core/settings-schema.js +4 -0
  40. package/dist/core/settings-schema.js.map +1 -1
  41. package/docs/compaction.md +5 -1
  42. package/docs/session-format.md +1 -1
  43. package/docs/settings.md +2 -1
  44. package/docs/workflows/api-reference.md +3 -1
  45. package/docs/workflows/operations.md +5 -2
  46. package/npm-shrinkwrap.json +32 -32
  47. package/package.json +3 -3
  48. package/schemas/settings.schema.json +14 -0
@@ -208,13 +208,85 @@ async function resolvePlannerAuth(resolveAuth, model) {
208
208
  return { failure: authFailureOutcome(error) };
209
209
  }
210
210
  }
211
- function freshResult(preparation, hardInputLimit, usage) {
211
+ /**
212
+ * Settle with `promise`, or reject as soon as `signal` aborts.
213
+ *
214
+ * Credential resolution may ignore the signal it is given; racing it keeps the
215
+ * planning time limit and cancellation a hard bound on the ladder either way.
216
+ */
217
+ function untilAborted(promise, signal) {
218
+ if (!signal)
219
+ return promise;
220
+ if (signal.aborted) {
221
+ void promise.catch(() => { });
222
+ return Promise.reject(signal.reason);
223
+ }
224
+ return new Promise((resolve, reject) => {
225
+ const onAbort = () => {
226
+ void promise.catch(() => { });
227
+ reject(signal.reason);
228
+ };
229
+ signal.addEventListener("abort", onAbort, { once: true });
230
+ promise.then((value) => {
231
+ signal.removeEventListener("abort", onAbort);
232
+ resolve(value);
233
+ }, (error) => {
234
+ signal.removeEventListener("abort", onAbort);
235
+ reject(error);
236
+ });
237
+ });
238
+ }
239
+ /** The message a terminal planner outcome reports, as recorded on a fresh rung. */
240
+ function terminalMessage(outcome) {
241
+ return outcome ? terminalError(outcome).message : undefined;
242
+ }
243
+ function freshResult(preparation, hardInputLimit, usage, freshReason) {
212
244
  const fresh = buildFreshContextWindow(preparation, hardInputLimit);
213
245
  return {
214
246
  ...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),
215
247
  rung: "fresh",
216
248
  keptTail: fresh.keptTail,
217
249
  ...(usage ? { usage } : {}),
250
+ ...(freshReason ? { freshReason } : {}),
251
+ };
252
+ }
253
+ /** The largest delay a platform timer accepts without clamping it to one millisecond. */
254
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
255
+ function startPlanningTimeLimit(timeoutMs, signal) {
256
+ // Any positive limit stays a limit: a sub-millisecond value rounds up rather than to "disabled".
257
+ const limitMs = timeoutMs !== undefined && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.ceil(timeoutMs) : 0;
258
+ const outcome = {
259
+ kind: "providerError",
260
+ message: `Compaction planning timed out after ${limitMs} ms`,
261
+ };
262
+ if (limitMs <= 0)
263
+ return { signal, expired: () => false, outcome, dispose: () => { } };
264
+ const controller = new AbortController();
265
+ let expired = false;
266
+ let timer;
267
+ const startedAt = Date.now();
268
+ // Re-arm in platform-sized steps so a limit beyond the timer maximum is honoured exactly.
269
+ const arm = () => {
270
+ const remainingMs = limitMs - (Date.now() - startedAt);
271
+ if (remainingMs <= 0) {
272
+ expired = true;
273
+ controller.abort(new Error(outcome.message));
274
+ return;
275
+ }
276
+ timer = setTimeout(arm, Math.min(remainingMs, MAX_TIMER_DELAY_MS));
277
+ };
278
+ arm();
279
+ const relayCancellation = () => controller.abort(signal?.reason);
280
+ signal?.addEventListener("abort", relayCancellation, { once: true });
281
+ return {
282
+ signal: controller.signal,
283
+ expired: () => expired,
284
+ outcome,
285
+ dispose: () => {
286
+ if (timer !== undefined)
287
+ clearTimeout(timer);
288
+ signal?.removeEventListener("abort", relayCancellation);
289
+ },
218
290
  };
219
291
  }
220
292
  /**
@@ -228,22 +300,45 @@ function freshResult(preparation, hardInputLimit, usage) {
228
300
  * Unavailable credentials are ladder control flow, not an early throw: a
229
301
  * borrowed candidate with its own working credentials can still rank the lines,
230
302
  * and a load-bearing caller still reaches the credential-free fresh rung.
303
+ *
304
+ * `planningTimeoutMs` bounds the whole planning phase. A planner that keeps
305
+ * streaming never trips the per-request stream idle deadline, and retries,
306
+ * trims and borrowed models each repeat it, so without this limit a mid-turn
307
+ * compaction could hold the active turn for as long as the provider allowed.
231
308
  */
232
309
  export async function runVerbatimCompaction(preparation, model, request) {
233
- const signal = request.signal;
234
- if (signal?.aborted)
310
+ if (request.signal?.aborted)
235
311
  throw new Error("Compaction cancelled");
312
+ const timeLimit = startPlanningTimeLimit(request.planningTimeoutMs, request.signal);
313
+ try {
314
+ return await runCompactionLadder(preparation, model, request, timeLimit);
315
+ }
316
+ finally {
317
+ timeLimit.dispose();
318
+ }
319
+ }
320
+ async function runCompactionLadder(preparation, model, request, timeLimit) {
321
+ const signal = request.signal;
236
322
  let plannerUsage;
237
323
  const plannerOptions = {
238
324
  streamFn: request.streamFn,
239
325
  sessionFilePath: request.sessionFilePath,
240
326
  retry: request.retry,
241
327
  callbacks: request.callbacks,
242
- signal,
328
+ signal: timeLimit.signal,
243
329
  onUsage: (usage) => {
244
330
  plannerUsage = addUsage(plannerUsage, usage);
245
331
  },
246
332
  };
333
+ // Credential waits count against the planning time limit too: each candidate's
334
+ // resolution sees the limit's signal and is abandoned the moment it aborts. Once
335
+ // it has aborted, no further lookup starts, so a borrower still walking its list
336
+ // cannot launch abandoned work in a resolver that ignores the signal.
337
+ const resolveAuth = (candidate) => {
338
+ if (timeLimit.signal?.aborted)
339
+ return Promise.reject(timeLimit.signal.reason);
340
+ return untilAborted(request.resolveAuth(candidate, timeLimit.signal), timeLimit.signal);
341
+ };
247
342
  const hardInputLimit = hardInputLimitFor(model);
248
343
  // A region below the planner minimum cannot be made rankable by changing
249
344
  // models, so no planner is invoked. Only a load-bearing caller can reach a
@@ -266,7 +361,7 @@ export async function runVerbatimCompaction(preparation, model, request) {
266
361
  const classify = request.classify;
267
362
  if (!classify)
268
363
  throw new Error("Compaction classifier is unavailable");
269
- const ranges = await planClassifierRanges(preparation.region, preparation.parameters, (context) => classify(selection.model, context, { signal }), plannerOptions);
364
+ const ranges = await planClassifierRanges(preparation.region, preparation.parameters, (context) => classify(selection.model, context, { signal: timeLimit.signal }), plannerOptions);
270
365
  return {
271
366
  ...plannedResult(preparation, ranges, undefined, plannerUsage, selection.fullId),
272
367
  backend: "classifier",
@@ -275,14 +370,16 @@ export async function runVerbatimCompaction(preparation, model, request) {
275
370
  catch (error) {
276
371
  if (signal?.aborted)
277
372
  throw new Error("Compaction cancelled");
278
- backendFailure = { kind: "providerError", message: error instanceof Error ? error.message : String(error) };
373
+ backendFailure = timeLimit.expired()
374
+ ? timeLimit.outcome
375
+ : { kind: "providerError", message: error instanceof Error ? error.message : String(error) };
279
376
  }
280
377
  }
281
378
  if (selection.kind === "morph") {
282
379
  try {
283
380
  const ranges = await planMorphRanges(preparation.region, preparation.parameters, {
284
- apiKey: await request.resolveMorphApiKey?.(),
285
- signal,
381
+ apiKey: await untilAborted(Promise.resolve(request.resolveMorphApiKey?.()), timeLimit.signal),
382
+ signal: timeLimit.signal,
286
383
  fetchFn: request.morphFetchFn,
287
384
  onDiagnostics: (diagnostics) => writeMorphDiagnosticSidecar(request.sessionFilePath, diagnostics),
288
385
  });
@@ -294,13 +391,15 @@ export async function runVerbatimCompaction(preparation, model, request) {
294
391
  catch (error) {
295
392
  if (signal?.aborted)
296
393
  throw new Error("Compaction cancelled");
297
- backendFailure = { kind: "providerError", message: error instanceof Error ? error.message : String(error) };
394
+ backendFailure = timeLimit.expired()
395
+ ? timeLimit.outcome
396
+ : { kind: "providerError", message: error instanceof Error ? error.message : String(error) };
298
397
  }
299
398
  }
300
399
  const primaryModel = selection.kind === "chat" ? selection.model : undefined;
301
400
  const primaryBudget = resolvePlannerRequest(primaryModel ?? model, request.thinkingLevel);
302
401
  const primaryAuth = primaryModel
303
- ? await resolvePlannerAuth(request.resolveAuth, primaryModel)
402
+ ? await resolvePlannerAuth(resolveAuth, primaryModel)
304
403
  : {
305
404
  failure: {
306
405
  kind: "providerError",
@@ -309,6 +408,8 @@ export async function runVerbatimCompaction(preparation, model, request) {
309
408
  : `Compaction backend ${selection.kind} is not yet available`,
310
409
  },
311
410
  };
411
+ if (signal?.aborted)
412
+ throw new Error("Compaction cancelled");
312
413
  let lastTerminal = "failure" in primaryAuth ? primaryAuth.failure : undefined;
313
414
  let borrowed = primaryModel !== model;
314
415
  let planner;
@@ -318,11 +419,22 @@ export async function runVerbatimCompaction(preparation, model, request) {
318
419
  else {
319
420
  if (primaryModel)
320
421
  attempted.add(plannerAttemptKey({ model: primaryModel, budget: primaryBudget, auth: {} }));
321
- planner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;
422
+ planner = borrow && !timeLimit.expired() ? await borrow(attempted, resolveAuth) : undefined;
322
423
  borrowed = planner !== undefined;
424
+ if (signal?.aborted)
425
+ throw new Error("Compaction cancelled");
323
426
  }
324
- while (planner) {
325
- const attempt = await planWithTrimming(preparation, planner, plannerOptions);
427
+ while (planner && !timeLimit.expired()) {
428
+ let attempt;
429
+ try {
430
+ attempt = await planWithTrimming(preparation, planner, plannerOptions);
431
+ }
432
+ catch (error) {
433
+ // The time limit aborted the in-flight request: end planning, not the run.
434
+ if (signal?.aborted || !timeLimit.expired())
435
+ throw error;
436
+ break;
437
+ }
326
438
  if (signal?.aborted)
327
439
  throw new Error("Compaction cancelled");
328
440
  if (attempt.kind === "planned") {
@@ -376,13 +488,15 @@ export async function runVerbatimCompaction(preparation, model, request) {
376
488
  }
377
489
  }
378
490
  attempted.add(plannerAttemptKey(planner));
379
- planner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;
491
+ planner = borrow && !timeLimit.expired() ? await borrow(attempted, resolveAuth) : undefined;
380
492
  borrowed = planner !== undefined;
381
493
  if (signal?.aborted)
382
494
  throw new Error("Compaction cancelled");
383
495
  }
496
+ if (timeLimit.expired())
497
+ lastTerminal = timeLimit.outcome;
384
498
  if (request.urgency !== "load_bearing")
385
499
  throw terminalError(lastTerminal);
386
- return freshResult(preparation, hardInputLimit, plannerUsage);
500
+ return freshResult(preparation, hardInputLimit, plannerUsage, terminalMessage(lastTerminal));
387
501
  }
388
502
  //# sourceMappingURL=compaction-runner.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAU9F,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,EAEN,6BAA6B,EAE7B,iBAAiB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAEhE,OAAO,EACN,wBAAwB,EACxB,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,EACd,qBAAqB,GACrB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,2BAA2B,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC5G,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3F,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAqDpE,SAAS,QAAQ,CAAC,KAAwB,EAAE,KAAY;IACvD,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,YAAY,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,YAAY,IAAI,CAAC,CAAC,CAAC;IAC5E,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,SAAS,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,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AAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YAC3G,CAAC;QACF,CAAC;QACD,SAAS,CAAC,GAAG,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC;QAC1C,OAAO,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC5E,QAAQ,GAAG,OAAO,KAAK,SAAS,CAAC;QACjC,IAAI,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAC9D,CAAC;IAED,IAAI,OAAO,CAAC,OAAO,KAAK,cAAc;QAAE,MAAM,aAAa,CAAC,YAAY,CAAC,CAAC;IAC1E,OAAO,WAAW,CAAC,WAAW,EAAE,cAAc,EAAE,YAAY,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type {\n\tClassifierApi,\n\tClassifierContext,\n\tClassifierModel,\n\tClassifierOptions,\n\tClassifierResult,\n\tRetryCallbacks,\n\tRetryPolicy,\n} from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { SessionEntry } from \"../session-manager-types.ts\";\nimport { planClassifierRanges } from \"./classifier-compaction.js\";\nimport { getKeptTailTokenEstimate, hasKeptTailTokenEstimate } from \"./compaction-boundary.js\";\nimport type {\n\tBorrowedPlanner,\n\tCompactedTranscript,\n\tCompactionPlannerModel,\n\tCompactionUrgency,\n\tPlannerAuth,\n\tRawLineRange,\n\tVerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { MIN_COMPACTABLE_REGION_LINES } from \"./compaction-types.js\";\nimport { reconstructCompactedTranscript, validateDeletedRanges } from \"./deleted-ranges.js\";\nimport {\n\ttype BorrowFallbackPlanner,\n\tcreateFallbackPlannerBorrower,\n\ttype FallbackPlannerContext,\n\tplannerAttemptKey,\n} from \"./fallback-planner.js\";\nimport type { CompactionModelSelection } from \"./model-resolver.js\";\nimport { planMorphRanges } from \"./morph-compaction.js\";\nimport { runPiSummaryFallback } from \"./pi-summary-fallback.js\";\nimport type { TerminalPlannerOutcome } from \"./planner-outcome.js\";\nimport {\n\tMALFORMED_OUTPUT_MESSAGE,\n\tNO_USABLE_RANGES_MESSAGE,\n\tplanDeletedLineRanges,\n\tRangePlanError,\n\tresolvePlannerRequest,\n} from \"./range-planner.js\";\nimport { writeMorphDiagnosticSidecar, writeSuccessDiagnosticSidecar } from \"./range-planner-diagnostics.js\";\nimport { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from \"./region-trimming.js\";\nimport { widenToWholeContextStats } from \"./whole-context-stats.js\";\n\nexport interface CompactionPlanOptions {\n\tstreamFn: StreamFn;\n\t/** Absolute path of the persisted session file. Undefined for in-memory sessions. */\n\tsessionFilePath?: string;\n\tretry?: RetryPolicy;\n\tcallbacks?: RetryCallbacks;\n}\n\n/** One compaction run's request. Urgency is required; there is no default. */\nexport interface CompactionRunRequest extends CompactionPlanOptions {\n\t/** Per-model credentials; a borrowed candidate uses its own, never the session model's. */\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tsignal?: AbortSignal;\n\t/** Inherited by the planner and never modified across attempts. */\n\tthinkingLevel: ThinkingLevel | undefined;\n\turgency: CompactionUrgency;\n\t/** Configured fallback candidates. Omitted means borrowing is impossible. */\n\tfallback?: FallbackPlannerContext;\n\tcompactionModel?: CompactionModelSelection;\n\tresolveMorphApiKey?: () => Promise<string | undefined>;\n\tmorphFetchFn?: typeof fetch;\n\tclassify?: (\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ClassifierOptions,\n\t) => Promise<ClassifierResult>;\n\tsummaryEntries?: SessionEntry[];\n\tcwd?: string;\n}\n\nexport type CompactionRungResult = CompactedTranscript & {\n\trung: \"planned\" | \"fresh\";\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** False only when the fresh rung had to drop the protected tail. */\n\tkeptTail: boolean;\n\t/** Aggregate usage across every planner request and retry in this run. */\n\tusage?: Usage;\n\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\tsummaryFirstKeptEntryId?: string;\n\tsummaryTokensBefore?: number;\n};\n\n/** Runner-internal fresh-window build: the transcript plus the tail decision. */\ninterface FreshWindowBuild {\n\ttranscript: CompactedTranscript;\n\tkeptTail: boolean;\n}\n\nfunction addUsage(total: Usage | undefined, usage: Usage): Usage {\n\tconst cacheWrite1h = (total?.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0);\n\tconst reasoning = (total?.reasoning ?? 0) + (usage.reasoning ?? 0);\n\treturn {\n\t\tinput: (total?.input ?? 0) + usage.input,\n\t\toutput: (total?.output ?? 0) + usage.output,\n\t\tcacheRead: (total?.cacheRead ?? 0) + usage.cacheRead,\n\t\tcacheWrite: (total?.cacheWrite ?? 0) + usage.cacheWrite,\n\t\t...(total?.cacheWrite1h !== undefined || usage.cacheWrite1h !== undefined ? { cacheWrite1h } : {}),\n\t\t...(total?.reasoning !== undefined || usage.reasoning !== undefined ? { reasoning } : {}),\n\t\ttotalTokens: (total?.totalTokens ?? 0) + usage.totalTokens,\n\t\tcost: {\n\t\t\tinput: (total?.cost.input ?? 0) + usage.cost.input,\n\t\t\toutput: (total?.cost.output ?? 0) + usage.cost.output,\n\t\t\tcacheRead: (total?.cost.cacheRead ?? 0) + usage.cost.cacheRead,\n\t\t\tcacheWrite: (total?.cost.cacheWrite ?? 0) + usage.cost.cacheWrite,\n\t\t\ttotal: (total?.cost.total ?? 0) + usage.cost.total,\n\t\t\ttotalFromProvider:\n\t\t\t\t(total === undefined || total.cost.totalFromProvider === true) && usage.cost.totalFromProvider === true,\n\t\t},\n\t};\n}\n\n/**\n * Calculate the single global line threshold from the prepared setting.\n *\n * Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5\n * ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the\n * compression ratio a real bound on output size, so protection can never enlarge the result.\n *\n * This is the untrimmed target. Overflow trimming does NOT reuse it:\n * `planWithTrimming` recomputes the threshold against each trimmed view, so the\n * planner is always asked to keep a proportion of the lines it actually\n * received rather than a proportion of a region it never saw.\n *\n * Retained as an exported helper for tests and consumers that need the\n * pre-trim target; production planning goes through `planWithTrimming`.\n */\nexport function targetKeepLines(preparation: VerbatimCompactionPreparation): number {\n\tconst region = preparation.region;\n\treturn Math.round(region.lines.length * preparation.parameters.compression_ratio);\n}\n\nfunction hardInputLimitFor(model: Model<Api>): number {\n\treturn model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n}\n\n/**\n * Widen region-level transcript stats to whole-context stats (#2052).\n *\n * `result.stats` must be the symmetric region-only stats produced by\n * `reconstructCompactedTranscript`; this adds the independently estimated kept\n * tail to the heuristic before count on both sides — and, only when the tail is\n * kept, to the after count — via the shared `widenToWholeContextStats`. The\n * authoritative `preparation.tokensBefore` is deliberately absent from this\n * comparison and travels separately for budgeting/display.\n */\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\treturn {\n\t\t...result,\n\t\tstats: widenToWholeContextStats(result.stats, getKeptTailTokenEstimate(preparation), keptTail),\n\t};\n}\n\n/**\n * Build a fresh context window and the tail decision that goes with it.\n *\n * Private on purpose: `keptTail` is runner bookkeeping that persistence needs in\n * order to write `firstKeptEntryId: null` when the protected tail is dropped. It\n * is deliberately absent from the public door's return value, which is exactly a\n * `CompactedTranscript`.\n */\nfunction buildFreshTranscript(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\tconst region = preparation.region;\n\tconst whole: RawLineRange[] = region.lines.length > 0 ? [{ start: 1, end: region.lines.length }] : [];\n\treturn reconstructCompactedTranscript(region, validateDeletedRanges(whole, region));\n}\n\nfunction buildFreshContextWindow(preparation: VerbatimCompactionPreparation, hardInputLimit: number): FreshWindowBuild {\n\tconst limit = Number.isFinite(hardInputLimit) && hardInputLimit > 0 ? hardInputLimit : Number.POSITIVE_INFINITY;\n\t// The rule is \"tail under the limit ⇒ tail kept\", so the comparison is the\n\t// tail alone. Explicit protected lines are a hard floor that survives either\n\t// way, and counting the reconstructed protected/marker text here would drop a\n\t// tail that fits. A rebuilt context that still cannot be sent is the post-tool\n\t// gate's problem, not a reason for this rung to discard more.\n\t// A kept tail with no registered estimate (a directly constructed\n\t// preparation) is dropped conservatively rather than assumed to fit (P1 #3010).\n\tconst keptTail =\n\t\tpreparation.keptTailMessageCount === 0 ||\n\t\t(hasKeptTailTokenEstimate(preparation) && getKeptTailTokenEstimate(preparation) <= limit);\n\treturn { transcript: buildFreshTranscript(preparation), keptTail };\n}\n\n/**\n * Discard every compactable line and start a fresh context window.\n *\n * TOTAL. No provider, no credentials, no network, no signal, no failure mode,\n * no `Promise`. Port of codex `compact_token_budget` →\n * `Session::start_new_context_window`. Atomic's system prompt, context files,\n * and skills are rebuilt per request and were never in the transcript, so they\n * survive automatically.\n *\n * The whole region is emitted as one deletion range and handed to the unchanged\n * `validateDeletedRanges` → `reconstructCompactedTranscript` path, which splits\n * around protected spans and folds prior markers.\n *\n * Returns exactly a `CompactedTranscript` — `text`, `ranges`, `stats` and\n * nothing else. Whether the `preserve_recent` tail survives is a persistence\n * concern and travels on `CompactionRungResult.keptTail`, not on this door.\n */\nexport function startNewContextWindow(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\treturn buildFreshTranscript(preparation);\n}\n\nfunction plannedResult(\n\tpreparation: VerbatimCompactionPreparation,\n\tranges: RawLineRange[],\n\tplannerModel: CompactionPlannerModel | undefined,\n\tusage: Usage | undefined,\n\tmodel: string,\n): CompactionRungResult {\n\tconst reconstructed = reconstructCompactedTranscript(\n\t\tpreparation.region,\n\t\tvalidateDeletedRanges(ranges, preparation.region),\n\t);\n\treturn {\n\t\t...withWholeContextStats(reconstructed, preparation, true),\n\t\trung: \"planned\",\n\t\tbackend: \"planner\",\n\t\tmodel,\n\t\t...(plannerModel ? { plannerModel } : {}),\n\t\tkeptTail: true,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\nfunction borrowedIdentity(planner: BorrowedPlanner): CompactionPlannerModel {\n\treturn {\n\t\tprovider: planner.model.provider,\n\t\tid: planner.model.id,\n\t\t...(planner.budget.reasoning ? { thinkingLevel: planner.budget.reasoning } : {}),\n\t};\n}\n\nfunction terminalError(outcome: TerminalPlannerOutcome | undefined): RangePlanError {\n\tif (!outcome) return new RangePlanError(MALFORMED_OUTPUT_MESSAGE, 1, \"\", false);\n\tif (outcome.kind === \"rateLimited\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tif (outcome.kind === \"overflowed\") {\n\t\treturn new RangePlanError(\n\t\t\t\"Compaction range planning exceeded the model context window\",\n\t\t\t1,\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t\toutcome.diagnosticPath,\n\t\t\toutcome,\n\t\t);\n\t}\n\tif (outcome.kind === \"providerError\" || outcome.kind === \"policyRefusal\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tconst message = outcome.category === \"malformed_output\" ? MALFORMED_OUTPUT_MESSAGE : NO_USABLE_RANGES_MESSAGE;\n\treturn new RangePlanError(message, 1, outcome.excerpt, false, outcome.diagnosticPath, outcome);\n}\n\ntype PlannerAttempt =\n\t| { kind: \"planned\"; ranges: RawLineRange[] }\n\t| { kind: \"terminal\"; outcome: TerminalPlannerOutcome };\n\n/**\n * Run one planner model, retrying the same model after oldest-first input\n * trimming when the request itself overflows the context window.\n *\n * Trimming continues until no strictly smaller view exists; `nextTrimOffset`\n * halves the remaining suffix, so the walk is finite. Only then is `overflowed`\n * terminal and the ladder advances.\n *\n * Each view gets its own keep target from `compression_ratio`. Reusing the\n * original whole-preparation target is what asked a halved 20-line region to\n * keep 10 of its 10 visible lines — a request for zero deletions, whose obedient\n * empty answer then hits the non-negotiable zero-range rejection. Extra\n * reduction still comes only from the head the runner withheld.\n */\nasync function planWithTrimming(\n\tpreparation: VerbatimCompactionPreparation,\n\tplanner: BorrowedPlanner,\n\toptions: CompactionPlanOptions & { signal?: AbortSignal },\n): Promise<PlannerAttempt> {\n\tlet offset = 0;\n\tfor (;;) {\n\t\tconst region = offset === 0 ? preparation.region : trimRegionHead(preparation.region, offset);\n\t\tif (!region) return { kind: \"terminal\", outcome: { kind: \"overflowed\" } };\n\t\tconst keepTarget = Math.max(\n\t\t\tregion.protectedLineNumbers?.size ?? 0,\n\t\t\tMath.round(region.lines.length * preparation.parameters.compression_ratio),\n\t\t);\n\t\tconst outcome = await planDeletedLineRanges(region, preparation.parameters, planner, keepTarget, options);\n\t\tif (outcome.kind === \"ranked\" || outcome.kind === \"recovered\") {\n\t\t\tif (offset === 0) return { kind: \"planned\", ranges: outcome.ranges };\n\t\t\tconst validated = validateDeletedRanges(outcome.ranges, region);\n\t\t\treturn { kind: \"planned\", ranges: rebaseTrimmedRanges(validated, offset) };\n\t\t}\n\t\tif (outcome.kind !== \"overflowed\") return { kind: \"terminal\", outcome };\n\t\tif (options.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tconst next = nextTrimOffset(preparation.region, offset);\n\t\tif (next === undefined) return { kind: \"terminal\", outcome };\n\t\toffset = next;\n\t}\n}\n\nconst MISSING_AUTH_MESSAGE = \"Compaction provider authentication is unavailable\";\n\n/**\n * A runner-local terminal cause with no provider attempt behind it.\n *\n * Missing credentials are not a provider outcome — no request was made — so no\n * synthetic response is fabricated and no diagnostic sidecar is written. It is\n * carried as `providerError` purely so the ladder can advance past it.\n */\nfunction authFailureOutcome(error: unknown): TerminalPlannerOutcome {\n\tconst message = error instanceof Error ? error.message : error === undefined ? MISSING_AUTH_MESSAGE : String(error);\n\treturn { kind: \"providerError\", message: message || MISSING_AUTH_MESSAGE };\n}\n\n/** Resolve one model's credentials, normalizing a rejection and `undefined` alike. */\nasync function resolvePlannerAuth(\n\tresolveAuth: CompactionRunRequest[\"resolveAuth\"],\n\tmodel: Model<Api>,\n): Promise<{ auth: PlannerAuth } | { failure: TerminalPlannerOutcome }> {\n\ttry {\n\t\tconst auth = await resolveAuth(model);\n\t\treturn auth ? { auth } : { failure: authFailureOutcome(undefined) };\n\t} catch (error) {\n\t\treturn { failure: authFailureOutcome(error) };\n\t}\n}\n\nfunction freshResult(\n\tpreparation: VerbatimCompactionPreparation,\n\thardInputLimit: number,\n\tusage?: Usage,\n): CompactionRungResult {\n\tconst fresh = buildFreshContextWindow(preparation, hardInputLimit);\n\treturn {\n\t\t...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),\n\t\trung: \"fresh\",\n\t\tkeptTail: fresh.keptTail,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\n/**\n * Produce one compacted transcript, tagged with the rung that produced it.\n *\n * The ladder is: the session model, then each configured fallback model\n * borrowed for one planner request, then — only under `load_bearing` urgency —\n * a fresh context window. A manual `/compact` runs at `recoverable` urgency and\n * therefore cannot reach the context-destroying rung; it fails honestly instead.\n *\n * Unavailable credentials are ladder control flow, not an early throw: a\n * borrowed candidate with its own working credentials can still rank the lines,\n * and a load-bearing caller still reaches the credential-free fresh rung.\n */\nexport async function runVerbatimCompaction(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n): Promise<CompactionRungResult> {\n\tconst signal = request.signal;\n\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tlet plannerUsage: Usage | undefined;\n\tconst plannerOptions = {\n\t\tstreamFn: request.streamFn,\n\t\tsessionFilePath: request.sessionFilePath,\n\t\tretry: request.retry,\n\t\tcallbacks: request.callbacks,\n\t\tsignal,\n\t\tonUsage: (usage: Usage) => {\n\t\t\tplannerUsage = addUsage(plannerUsage, usage);\n\t\t},\n\t};\n\tconst hardInputLimit = hardInputLimitFor(model);\n\n\t// A region below the planner minimum cannot be made rankable by changing\n\t// models, so no planner is invoked. Only a load-bearing caller can reach a\n\t// preparation this small; recoverable callers were refused before the runner.\n\tif (preparation.region.lines.length < MIN_COMPACTABLE_REGION_LINES) {\n\t\tif (request.urgency !== \"load_bearing\") throw new RangePlanError(NO_USABLE_RANGES_MESSAGE, 0, \"\", false);\n\t\treturn freshResult(preparation, hardInputLimit);\n\t}\n\n\tconst selection = request.compactionModel ?? { kind: \"chat\", fullId: `${model.provider}/${model.id}`, model };\n\tconst attempted = new Set<string>();\n\t// One borrower per run owns the monotonic cursor, so the configured list is\n\t// walked exactly once no matter how many terminal outcomes occur.\n\tconst borrow: BorrowFallbackPlanner | undefined = request.fallback\n\t\t? createFallbackPlannerBorrower({ ...request.fallback, selectedModelId: selection.fullId })\n\t\t: undefined;\n\tlet backendFailure: TerminalPlannerOutcome | undefined;\n\tif (selection.kind === \"classifier\") {\n\t\ttry {\n\t\t\tconst classify = request.classify;\n\t\t\tif (!classify) throw new Error(\"Compaction classifier is unavailable\");\n\t\t\tconst ranges = await planClassifierRanges(\n\t\t\t\tpreparation.region,\n\t\t\t\tpreparation.parameters,\n\t\t\t\t(context) => classify(selection.model, context, { signal }),\n\t\t\t\tplannerOptions,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\t...plannedResult(preparation, ranges, undefined, plannerUsage, selection.fullId),\n\t\t\t\tbackend: \"classifier\",\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\tbackendFailure = { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\tif (selection.kind === \"morph\") {\n\t\ttry {\n\t\t\tconst ranges = await planMorphRanges(preparation.region, preparation.parameters, {\n\t\t\t\tapiKey: await request.resolveMorphApiKey?.(),\n\t\t\t\tsignal,\n\t\t\t\tfetchFn: request.morphFetchFn,\n\t\t\t\tonDiagnostics: (diagnostics) => writeMorphDiagnosticSidecar(request.sessionFilePath, diagnostics),\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...plannedResult(preparation, ranges, undefined, undefined, selection.fullId),\n\t\t\t\tbackend: \"morph\",\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\tbackendFailure = { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\tconst primaryModel = selection.kind === \"chat\" ? selection.model : undefined;\n\tconst primaryBudget = resolvePlannerRequest(primaryModel ?? model, request.thinkingLevel);\n\tconst primaryAuth = primaryModel\n\t\t? await resolvePlannerAuth(request.resolveAuth, primaryModel)\n\t\t: {\n\t\t\t\tfailure: {\n\t\t\t\t\tkind: \"providerError\" as const,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\tbackendFailure?.kind === \"providerError\"\n\t\t\t\t\t\t\t? backendFailure.message\n\t\t\t\t\t\t\t: `Compaction backend ${selection.kind} is not yet available`,\n\t\t\t\t},\n\t\t\t};\n\tlet lastTerminal: TerminalPlannerOutcome | undefined = \"failure\" in primaryAuth ? primaryAuth.failure : undefined;\n\tlet borrowed = primaryModel !== model;\n\tlet planner: BorrowedPlanner | undefined;\n\n\tif (primaryModel && \"auth\" in primaryAuth) {\n\t\tplanner = { model: primaryModel, budget: primaryBudget, auth: primaryAuth.auth };\n\t} else {\n\t\tif (primaryModel) attempted.add(plannerAttemptKey({ model: primaryModel, budget: primaryBudget, auth: {} }));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t}\n\n\twhile (planner) {\n\t\tconst attempt = await planWithTrimming(preparation, planner, plannerOptions);\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (attempt.kind === \"planned\") {\n\t\t\tconst plannerModel = borrowed ? borrowedIdentity(planner) : undefined;\n\t\t\tif (plannerModel) {\n\t\t\t\t// Best-effort: the durable entry already records the borrowed model;\n\t\t\t\t// a sidecar write failure never affects compaction success.\n\t\t\t\twriteSuccessDiagnosticSidecar({\n\t\t\t\t\tsessionFilePath: request.sessionFilePath,\n\t\t\t\t\tmodel: planner.model,\n\t\t\t\t\tsuccessCategory: \"borrowed_planner\",\n\t\t\t\t\t...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn plannedResult(\n\t\t\t\tpreparation,\n\t\t\t\tattempt.ranges,\n\t\t\t\tplannerModel,\n\t\t\t\tplannerUsage,\n\t\t\t\t`${planner.model.provider}/${planner.model.id}`,\n\t\t\t);\n\t\t}\n\t\tlastTerminal = attempt.outcome;\n\t\tif (attempt.outcome.kind === \"policyRefusal\" && request.summaryEntries) {\n\t\t\ttry {\n\t\t\t\tconst summary = await runPiSummaryFallback(request.summaryEntries, preparation.settings, planner, {\n\t\t\t\t\t...plannerOptions,\n\t\t\t\t\tcwd: request.cwd,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\ttext: summary.summary,\n\t\t\t\t\tranges: [],\n\t\t\t\t\tkeptRanges: [],\n\t\t\t\t\tstats: {\n\t\t\t\t\t\tlinesBefore: preparation.region.lines.length,\n\t\t\t\t\t\tlinesDeleted: 0,\n\t\t\t\t\t\tlinesKept: summary.summary.split(\"\\n\").length,\n\t\t\t\t\t\trangeCount: 0,\n\t\t\t\t\t\ttokensBefore: summary.tokensBefore,\n\t\t\t\t\t\ttokensAfter: summary.tokensAfter,\n\t\t\t\t\t\tpercentReduction:\n\t\t\t\t\t\t\tsummary.tokensBefore > 0 ? 100 * (1 - summary.tokensAfter / summary.tokensBefore) : 0,\n\t\t\t\t\t},\n\t\t\t\t\trung: \"planned\",\n\t\t\t\t\tkeptTail: true,\n\t\t\t\t\tbackend: \"summary\",\n\t\t\t\t\tmodel: `${planner.model.provider}/${planner.model.id}`,\n\t\t\t\t\tsummary: { readFiles: summary.readFiles, modifiedFiles: summary.modifiedFiles },\n\t\t\t\t\tsummaryFirstKeptEntryId: summary.firstKeptEntryId,\n\t\t\t\t\tsummaryTokensBefore: summary.tokensBefore,\n\t\t\t\t\t...(plannerUsage ? { usage: plannerUsage } : {}),\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\t\tlastTerminal = { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t\t}\n\t\t}\n\t\tattempted.add(plannerAttemptKey(planner));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\tif (request.urgency !== \"load_bearing\") throw terminalError(lastTerminal);\n\treturn freshResult(preparation, hardInputLimit, plannerUsage);\n}\n"]}
1
+ {"version":3,"file":"compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAU9F,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,EAEN,6BAA6B,EAE7B,iBAAiB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAEhE,OAAO,EACN,wBAAwB,EACxB,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,EACd,qBAAqB,GACrB,MAAM,oBAAoB,CAAC;AAC5B,OA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CAAC,KAAK,CAAC,EAAE,CAAC;YAC3G,CAAC;QACF,CAAC;QACD,SAAS,CAAC,GAAG,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC;QAC1C,OAAO,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC5F,QAAQ,GAAG,OAAO,KAAK,SAAS,CAAC;QACjC,IAAI,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAC9D,CAAC;IAED,IAAI,SAAS,CAAC,OAAO,EAAE;QAAE,YAAY,GAAG,SAAS,CAAC,OAAO,CAAC;IAC1D,IAAI,OAAO,CAAC,OAAO,KAAK,cAAc;QAAE,MAAM,aAAa,CAAC,YAAY,CAAC,CAAC;IAC1E,OAAO,WAAW,CAAC,WAAW,EAAE,cAAc,EAAE,YAAY,EAAE,eAAe,CAAC,YAAY,CAAC,CAAC,CAAC;AAC9F,CAAC","sourcesContent":["import type {\n\tClassifierApi,\n\tClassifierContext,\n\tClassifierModel,\n\tClassifierOptions,\n\tClassifierResult,\n\tRetryCallbacks,\n\tRetryPolicy,\n} from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { SessionEntry } from \"../session-manager-types.ts\";\nimport { planClassifierRanges } from \"./classifier-compaction.js\";\nimport { getKeptTailTokenEstimate, hasKeptTailTokenEstimate } from \"./compaction-boundary.js\";\nimport type {\n\tBorrowedPlanner,\n\tCompactedTranscript,\n\tCompactionPlannerModel,\n\tCompactionUrgency,\n\tPlannerAuth,\n\tRawLineRange,\n\tVerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { MIN_COMPACTABLE_REGION_LINES } from \"./compaction-types.js\";\nimport { reconstructCompactedTranscript, validateDeletedRanges } from \"./deleted-ranges.js\";\nimport {\n\ttype BorrowFallbackPlanner,\n\tcreateFallbackPlannerBorrower,\n\ttype FallbackPlannerContext,\n\tplannerAttemptKey,\n} from \"./fallback-planner.js\";\nimport type { CompactionModelSelection } from \"./model-resolver.js\";\nimport { planMorphRanges } from \"./morph-compaction.js\";\nimport { runPiSummaryFallback } from \"./pi-summary-fallback.js\";\nimport type { TerminalPlannerOutcome } from \"./planner-outcome.js\";\nimport {\n\tMALFORMED_OUTPUT_MESSAGE,\n\tNO_USABLE_RANGES_MESSAGE,\n\tplanDeletedLineRanges,\n\tRangePlanError,\n\tresolvePlannerRequest,\n} from \"./range-planner.js\";\nimport { writeMorphDiagnosticSidecar, writeSuccessDiagnosticSidecar } from \"./range-planner-diagnostics.js\";\nimport { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from \"./region-trimming.js\";\nimport { widenToWholeContextStats } from \"./whole-context-stats.js\";\n\nexport interface CompactionPlanOptions {\n\tstreamFn: StreamFn;\n\t/** Absolute path of the persisted session file. Undefined for in-memory sessions. */\n\tsessionFilePath?: string;\n\tretry?: RetryPolicy;\n\tcallbacks?: RetryCallbacks;\n}\n\n/** One compaction run's request. Urgency is required; there is no default. */\nexport interface CompactionRunRequest extends CompactionPlanOptions {\n\t/**\n\t * Per-model credentials; a borrowed candidate uses its own, never the session model's.\n\t * `signal` aborts when the run is cancelled or its planning time limit runs out.\n\t */\n\tresolveAuth: (model: Model<Api>, signal?: AbortSignal) => Promise<PlannerAuth | undefined>;\n\tsignal?: AbortSignal;\n\t/**\n\t * Wall-clock limit on model planning: every backend, planner request, retry, overflow trim\n\t * and borrowed fallback model. When it runs out, the in-flight request is aborted and the\n\t * ladder ends as if every planner had failed (#4198). Omitted or non-positive means no limit.\n\t */\n\tplanningTimeoutMs?: number;\n\t/** Inherited by the planner and never modified across attempts. */\n\tthinkingLevel: ThinkingLevel | undefined;\n\turgency: CompactionUrgency;\n\t/** Configured fallback candidates. Omitted means borrowing is impossible. */\n\tfallback?: FallbackPlannerContext;\n\tcompactionModel?: CompactionModelSelection;\n\tresolveMorphApiKey?: () => Promise<string | undefined>;\n\tmorphFetchFn?: typeof fetch;\n\tclassify?: (\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ClassifierOptions,\n\t) => Promise<ClassifierResult>;\n\tsummaryEntries?: SessionEntry[];\n\tcwd?: string;\n}\n\nexport type CompactionRungResult = CompactedTranscript & {\n\trung: \"planned\" | \"fresh\";\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** False only when the fresh rung had to drop the protected tail. */\n\tkeptTail: boolean;\n\t/** Aggregate usage across every planner request and retry in this run. */\n\tusage?: Usage;\n\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\tsummaryFirstKeptEntryId?: string;\n\tsummaryTokensBefore?: number;\n\t/** Present only on the fresh rung after planning failed: why no planner could rank the lines. */\n\tfreshReason?: string;\n};\n\n/** Runner-internal fresh-window build: the transcript plus the tail decision. */\ninterface FreshWindowBuild {\n\ttranscript: CompactedTranscript;\n\tkeptTail: boolean;\n}\n\nfunction addUsage(total: Usage | undefined, usage: Usage): Usage {\n\tconst cacheWrite1h = (total?.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0);\n\tconst reasoning = (total?.reasoning ?? 0) + (usage.reasoning ?? 0);\n\treturn {\n\t\tinput: (total?.input ?? 0) + usage.input,\n\t\toutput: (total?.output ?? 0) + usage.output,\n\t\tcacheRead: (total?.cacheRead ?? 0) + usage.cacheRead,\n\t\tcacheWrite: (total?.cacheWrite ?? 0) + usage.cacheWrite,\n\t\t...(total?.cacheWrite1h !== undefined || usage.cacheWrite1h !== undefined ? { cacheWrite1h } : {}),\n\t\t...(total?.reasoning !== undefined || usage.reasoning !== undefined ? { reasoning } : {}),\n\t\ttotalTokens: (total?.totalTokens ?? 0) + usage.totalTokens,\n\t\tcost: {\n\t\t\tinput: (total?.cost.input ?? 0) + usage.cost.input,\n\t\t\toutput: (total?.cost.output ?? 0) + usage.cost.output,\n\t\t\tcacheRead: (total?.cost.cacheRead ?? 0) + usage.cost.cacheRead,\n\t\t\tcacheWrite: (total?.cost.cacheWrite ?? 0) + usage.cost.cacheWrite,\n\t\t\ttotal: (total?.cost.total ?? 0) + usage.cost.total,\n\t\t\ttotalFromProvider:\n\t\t\t\t(total === undefined || total.cost.totalFromProvider === true) && usage.cost.totalFromProvider === true,\n\t\t},\n\t};\n}\n\n/**\n * Calculate the single global line threshold from the prepared setting.\n *\n * Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5\n * ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the\n * compression ratio a real bound on output size, so protection can never enlarge the result.\n *\n * This is the untrimmed target. Overflow trimming does NOT reuse it:\n * `planWithTrimming` recomputes the threshold against each trimmed view, so the\n * planner is always asked to keep a proportion of the lines it actually\n * received rather than a proportion of a region it never saw.\n *\n * Retained as an exported helper for tests and consumers that need the\n * pre-trim target; production planning goes through `planWithTrimming`.\n */\nexport function targetKeepLines(preparation: VerbatimCompactionPreparation): number {\n\tconst region = preparation.region;\n\treturn Math.round(region.lines.length * preparation.parameters.compression_ratio);\n}\n\nfunction hardInputLimitFor(model: Model<Api>): number {\n\treturn model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n}\n\n/**\n * Widen region-level transcript stats to whole-context stats (#2052).\n *\n * `result.stats` must be the symmetric region-only stats produced by\n * `reconstructCompactedTranscript`; this adds the independently estimated kept\n * tail to the heuristic before count on both sides — and, only when the tail is\n * kept, to the after count — via the shared `widenToWholeContextStats`. The\n * authoritative `preparation.tokensBefore` is deliberately absent from this\n * comparison and travels separately for budgeting/display.\n */\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\treturn {\n\t\t...result,\n\t\tstats: widenToWholeContextStats(result.stats, getKeptTailTokenEstimate(preparation), keptTail),\n\t};\n}\n\n/**\n * Build a fresh context window and the tail decision that goes with it.\n *\n * Private on purpose: `keptTail` is runner bookkeeping that persistence needs in\n * order to write `firstKeptEntryId: null` when the protected tail is dropped. It\n * is deliberately absent from the public door's return value, which is exactly a\n * `CompactedTranscript`.\n */\nfunction buildFreshTranscript(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\tconst region = preparation.region;\n\tconst whole: RawLineRange[] = region.lines.length > 0 ? [{ start: 1, end: region.lines.length }] : [];\n\treturn reconstructCompactedTranscript(region, validateDeletedRanges(whole, region));\n}\n\nfunction buildFreshContextWindow(preparation: VerbatimCompactionPreparation, hardInputLimit: number): FreshWindowBuild {\n\tconst limit = Number.isFinite(hardInputLimit) && hardInputLimit > 0 ? hardInputLimit : Number.POSITIVE_INFINITY;\n\t// The rule is \"tail under the limit ⇒ tail kept\", so the comparison is the\n\t// tail alone. Explicit protected lines are a hard floor that survives either\n\t// way, and counting the reconstructed protected/marker text here would drop a\n\t// tail that fits. A rebuilt context that still cannot be sent is the post-tool\n\t// gate's problem, not a reason for this rung to discard more.\n\t// A kept tail with no registered estimate (a directly constructed\n\t// preparation) is dropped conservatively rather than assumed to fit (P1 #3010).\n\tconst keptTail =\n\t\tpreparation.keptTailMessageCount === 0 ||\n\t\t(hasKeptTailTokenEstimate(preparation) && getKeptTailTokenEstimate(preparation) <= limit);\n\treturn { transcript: buildFreshTranscript(preparation), keptTail };\n}\n\n/**\n * Discard every compactable line and start a fresh context window.\n *\n * TOTAL. No provider, no credentials, no network, no signal, no failure mode,\n * no `Promise`. Port of codex `compact_token_budget` →\n * `Session::start_new_context_window`. Atomic's system prompt, context files,\n * and skills are rebuilt per request and were never in the transcript, so they\n * survive automatically.\n *\n * The whole region is emitted as one deletion range and handed to the unchanged\n * `validateDeletedRanges` → `reconstructCompactedTranscript` path, which splits\n * around protected spans and folds prior markers.\n *\n * Returns exactly a `CompactedTranscript` — `text`, `ranges`, `stats` and\n * nothing else. Whether the `preserve_recent` tail survives is a persistence\n * concern and travels on `CompactionRungResult.keptTail`, not on this door.\n */\nexport function startNewContextWindow(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\treturn buildFreshTranscript(preparation);\n}\n\nfunction plannedResult(\n\tpreparation: VerbatimCompactionPreparation,\n\tranges: RawLineRange[],\n\tplannerModel: CompactionPlannerModel | undefined,\n\tusage: Usage | undefined,\n\tmodel: string,\n): CompactionRungResult {\n\tconst reconstructed = reconstructCompactedTranscript(\n\t\tpreparation.region,\n\t\tvalidateDeletedRanges(ranges, preparation.region),\n\t);\n\treturn {\n\t\t...withWholeContextStats(reconstructed, preparation, true),\n\t\trung: \"planned\",\n\t\tbackend: \"planner\",\n\t\tmodel,\n\t\t...(plannerModel ? { plannerModel } : {}),\n\t\tkeptTail: true,\n\t\t...(usage ? { usage } : {}),\n\t};\n}\n\nfunction borrowedIdentity(planner: BorrowedPlanner): CompactionPlannerModel {\n\treturn {\n\t\tprovider: planner.model.provider,\n\t\tid: planner.model.id,\n\t\t...(planner.budget.reasoning ? { thinkingLevel: planner.budget.reasoning } : {}),\n\t};\n}\n\nfunction terminalError(outcome: TerminalPlannerOutcome | undefined): RangePlanError {\n\tif (!outcome) return new RangePlanError(MALFORMED_OUTPUT_MESSAGE, 1, \"\", false);\n\tif (outcome.kind === \"rateLimited\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tif (outcome.kind === \"overflowed\") {\n\t\treturn new RangePlanError(\n\t\t\t\"Compaction range planning exceeded the model context window\",\n\t\t\t1,\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t\toutcome.diagnosticPath,\n\t\t\toutcome,\n\t\t);\n\t}\n\tif (outcome.kind === \"providerError\" || outcome.kind === \"policyRefusal\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tconst message = outcome.category === \"malformed_output\" ? MALFORMED_OUTPUT_MESSAGE : NO_USABLE_RANGES_MESSAGE;\n\treturn new RangePlanError(message, 1, outcome.excerpt, false, outcome.diagnosticPath, outcome);\n}\n\ntype PlannerAttempt =\n\t| { kind: \"planned\"; ranges: RawLineRange[] }\n\t| { kind: \"terminal\"; outcome: TerminalPlannerOutcome };\n\n/**\n * Run one planner model, retrying the same model after oldest-first input\n * trimming when the request itself overflows the context window.\n *\n * Trimming continues until no strictly smaller view exists; `nextTrimOffset`\n * halves the remaining suffix, so the walk is finite. Only then is `overflowed`\n * terminal and the ladder advances.\n *\n * Each view gets its own keep target from `compression_ratio`. Reusing the\n * original whole-preparation target is what asked a halved 20-line region to\n * keep 10 of its 10 visible lines — a request for zero deletions, whose obedient\n * empty answer then hits the non-negotiable zero-range rejection. Extra\n * reduction still comes only from the head the runner withheld.\n */\nasync function planWithTrimming(\n\tpreparation: VerbatimCompactionPreparation,\n\tplanner: BorrowedPlanner,\n\toptions: CompactionPlanOptions & { signal?: AbortSignal },\n): Promise<PlannerAttempt> {\n\tlet offset = 0;\n\tfor (;;) {\n\t\tconst region = offset === 0 ? preparation.region : trimRegionHead(preparation.region, offset);\n\t\tif (!region) return { kind: \"terminal\", outcome: { kind: \"overflowed\" } };\n\t\tconst keepTarget = Math.max(\n\t\t\tregion.protectedLineNumbers?.size ?? 0,\n\t\t\tMath.round(region.lines.length * preparation.parameters.compression_ratio),\n\t\t);\n\t\tconst outcome = await planDeletedLineRanges(region, preparation.parameters, planner, keepTarget, options);\n\t\tif (outcome.kind === \"ranked\" || outcome.kind === \"recovered\") {\n\t\t\tif (offset === 0) return { kind: \"planned\", ranges: outcome.ranges };\n\t\t\tconst validated = validateDeletedRanges(outcome.ranges, region);\n\t\t\treturn { kind: \"planned\", ranges: rebaseTrimmedRanges(validated, offset) };\n\t\t}\n\t\tif (outcome.kind !== \"overflowed\") return { kind: \"terminal\", outcome };\n\t\tif (options.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tconst next = nextTrimOffset(preparation.region, offset);\n\t\tif (next === undefined) return { kind: \"terminal\", outcome };\n\t\toffset = next;\n\t}\n}\n\nconst MISSING_AUTH_MESSAGE = \"Compaction provider authentication is unavailable\";\n\n/**\n * A runner-local terminal cause with no provider attempt behind it.\n *\n * Missing credentials are not a provider outcome — no request was made — so no\n * synthetic response is fabricated and no diagnostic sidecar is written. It is\n * carried as `providerError` purely so the ladder can advance past it.\n */\nfunction authFailureOutcome(error: unknown): TerminalPlannerOutcome {\n\tconst message = error instanceof Error ? error.message : error === undefined ? MISSING_AUTH_MESSAGE : String(error);\n\treturn { kind: \"providerError\", message: message || MISSING_AUTH_MESSAGE };\n}\n\n/** Resolve one model's credentials, normalizing a rejection and `undefined` alike. */\nasync function resolvePlannerAuth(\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>,\n\tmodel: Model<Api>,\n): Promise<{ auth: PlannerAuth } | { failure: TerminalPlannerOutcome }> {\n\ttry {\n\t\tconst auth = await resolveAuth(model);\n\t\treturn auth ? { auth } : { failure: authFailureOutcome(undefined) };\n\t} catch (error) {\n\t\treturn { failure: authFailureOutcome(error) };\n\t}\n}\n\n/**\n * Settle with `promise`, or reject as soon as `signal` aborts.\n *\n * Credential resolution may ignore the signal it is given; racing it keeps the\n * planning time limit and cancellation a hard bound on the ladder either way.\n */\nfunction untilAborted<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n\tif (!signal) return promise;\n\tif (signal.aborted) {\n\t\tvoid promise.catch(() => {});\n\t\treturn Promise.reject(signal.reason);\n\t}\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst onAbort = () => {\n\t\t\tvoid promise.catch(() => {});\n\t\t\treject(signal.reason);\n\t\t};\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tpromise.then(\n\t\t\t(value) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\n/** The message a terminal planner outcome reports, as recorded on a fresh rung. */\nfunction terminalMessage(outcome: TerminalPlannerOutcome | undefined): string | undefined {\n\treturn outcome ? terminalError(outcome).message : undefined;\n}\n\nfunction freshResult(\n\tpreparation: VerbatimCompactionPreparation,\n\thardInputLimit: number,\n\tusage?: Usage,\n\tfreshReason?: string,\n): CompactionRungResult {\n\tconst fresh = buildFreshContextWindow(preparation, hardInputLimit);\n\treturn {\n\t\t...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),\n\t\trung: \"fresh\",\n\t\tkeptTail: fresh.keptTail,\n\t\t...(usage ? { usage } : {}),\n\t\t...(freshReason ? { freshReason } : {}),\n\t};\n}\n\n/** The largest delay a platform timer accepts without clamping it to one millisecond. */\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\n\n/**\n * One run's planning time limit.\n *\n * `signal` aborts on caller cancellation or when the limit runs out; only the latter sets\n * `expired`, so the ladder can tell a timeout (end planning, keep going) from cancellation\n * (stop the whole run).\n */\ninterface PlanningTimeLimit {\n\treadonly signal: AbortSignal | undefined;\n\texpired(): boolean;\n\treadonly outcome: TerminalPlannerOutcome;\n\tdispose(): void;\n}\n\nfunction startPlanningTimeLimit(timeoutMs: number | undefined, signal: AbortSignal | undefined): PlanningTimeLimit {\n\t// Any positive limit stays a limit: a sub-millisecond value rounds up rather than to \"disabled\".\n\tconst limitMs = timeoutMs !== undefined && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.ceil(timeoutMs) : 0;\n\tconst outcome: TerminalPlannerOutcome = {\n\t\tkind: \"providerError\",\n\t\tmessage: `Compaction planning timed out after ${limitMs} ms`,\n\t};\n\tif (limitMs <= 0) return { signal, expired: () => false, outcome, dispose: () => {} };\n\tconst controller = new AbortController();\n\tlet expired = false;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst startedAt = Date.now();\n\t// Re-arm in platform-sized steps so a limit beyond the timer maximum is honoured exactly.\n\tconst arm = () => {\n\t\tconst remainingMs = limitMs - (Date.now() - startedAt);\n\t\tif (remainingMs <= 0) {\n\t\t\texpired = true;\n\t\t\tcontroller.abort(new Error(outcome.message));\n\t\t\treturn;\n\t\t}\n\t\ttimer = setTimeout(arm, Math.min(remainingMs, MAX_TIMER_DELAY_MS));\n\t};\n\tarm();\n\tconst relayCancellation = () => controller.abort(signal?.reason);\n\tsignal?.addEventListener(\"abort\", relayCancellation, { once: true });\n\treturn {\n\t\tsignal: controller.signal,\n\t\texpired: () => expired,\n\t\toutcome,\n\t\tdispose: () => {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\tsignal?.removeEventListener(\"abort\", relayCancellation);\n\t\t},\n\t};\n}\n\n/**\n * Produce one compacted transcript, tagged with the rung that produced it.\n *\n * The ladder is: the session model, then each configured fallback model\n * borrowed for one planner request, then — only under `load_bearing` urgency —\n * a fresh context window. A manual `/compact` runs at `recoverable` urgency and\n * therefore cannot reach the context-destroying rung; it fails honestly instead.\n *\n * Unavailable credentials are ladder control flow, not an early throw: a\n * borrowed candidate with its own working credentials can still rank the lines,\n * and a load-bearing caller still reaches the credential-free fresh rung.\n *\n * `planningTimeoutMs` bounds the whole planning phase. A planner that keeps\n * streaming never trips the per-request stream idle deadline, and retries,\n * trims and borrowed models each repeat it, so without this limit a mid-turn\n * compaction could hold the active turn for as long as the provider allowed.\n */\nexport async function runVerbatimCompaction(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n): Promise<CompactionRungResult> {\n\tif (request.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tconst timeLimit = startPlanningTimeLimit(request.planningTimeoutMs, request.signal);\n\ttry {\n\t\treturn await runCompactionLadder(preparation, model, request, timeLimit);\n\t} finally {\n\t\ttimeLimit.dispose();\n\t}\n}\n\nasync function runCompactionLadder(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n\ttimeLimit: PlanningTimeLimit,\n): Promise<CompactionRungResult> {\n\tconst signal = request.signal;\n\tlet plannerUsage: Usage | undefined;\n\tconst plannerOptions = {\n\t\tstreamFn: request.streamFn,\n\t\tsessionFilePath: request.sessionFilePath,\n\t\tretry: request.retry,\n\t\tcallbacks: request.callbacks,\n\t\tsignal: timeLimit.signal,\n\t\tonUsage: (usage: Usage) => {\n\t\t\tplannerUsage = addUsage(plannerUsage, usage);\n\t\t},\n\t};\n\t// Credential waits count against the planning time limit too: each candidate's\n\t// resolution sees the limit's signal and is abandoned the moment it aborts. Once\n\t// it has aborted, no further lookup starts, so a borrower still walking its list\n\t// cannot launch abandoned work in a resolver that ignores the signal.\n\tconst resolveAuth = (candidate: Model<Api>): Promise<PlannerAuth | undefined> => {\n\t\tif (timeLimit.signal?.aborted) return Promise.reject(timeLimit.signal.reason);\n\t\treturn untilAborted(request.resolveAuth(candidate, timeLimit.signal), timeLimit.signal);\n\t};\n\tconst hardInputLimit = hardInputLimitFor(model);\n\n\t// A region below the planner minimum cannot be made rankable by changing\n\t// models, so no planner is invoked. Only a load-bearing caller can reach a\n\t// preparation this small; recoverable callers were refused before the runner.\n\tif (preparation.region.lines.length < MIN_COMPACTABLE_REGION_LINES) {\n\t\tif (request.urgency !== \"load_bearing\") throw new RangePlanError(NO_USABLE_RANGES_MESSAGE, 0, \"\", false);\n\t\treturn freshResult(preparation, hardInputLimit);\n\t}\n\n\tconst selection = request.compactionModel ?? { kind: \"chat\", fullId: `${model.provider}/${model.id}`, model };\n\tconst attempted = new Set<string>();\n\t// One borrower per run owns the monotonic cursor, so the configured list is\n\t// walked exactly once no matter how many terminal outcomes occur.\n\tconst borrow: BorrowFallbackPlanner | undefined = request.fallback\n\t\t? createFallbackPlannerBorrower({ ...request.fallback, selectedModelId: selection.fullId })\n\t\t: undefined;\n\tlet backendFailure: TerminalPlannerOutcome | undefined;\n\tif (selection.kind === \"classifier\") {\n\t\ttry {\n\t\t\tconst classify = request.classify;\n\t\t\tif (!classify) throw new Error(\"Compaction classifier is unavailable\");\n\t\t\tconst ranges = await planClassifierRanges(\n\t\t\t\tpreparation.region,\n\t\t\t\tpreparation.parameters,\n\t\t\t\t(context) => classify(selection.model, context, { signal: timeLimit.signal }),\n\t\t\t\tplannerOptions,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\t...plannedResult(preparation, ranges, undefined, plannerUsage, selection.fullId),\n\t\t\t\tbackend: \"classifier\",\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\tbackendFailure = timeLimit.expired()\n\t\t\t\t? timeLimit.outcome\n\t\t\t\t: { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\tif (selection.kind === \"morph\") {\n\t\ttry {\n\t\t\tconst ranges = await planMorphRanges(preparation.region, preparation.parameters, {\n\t\t\t\tapiKey: await untilAborted(Promise.resolve(request.resolveMorphApiKey?.()), timeLimit.signal),\n\t\t\t\tsignal: timeLimit.signal,\n\t\t\t\tfetchFn: request.morphFetchFn,\n\t\t\t\tonDiagnostics: (diagnostics) => writeMorphDiagnosticSidecar(request.sessionFilePath, diagnostics),\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...plannedResult(preparation, ranges, undefined, undefined, selection.fullId),\n\t\t\t\tbackend: \"morph\",\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\tbackendFailure = timeLimit.expired()\n\t\t\t\t? timeLimit.outcome\n\t\t\t\t: { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\tconst primaryModel = selection.kind === \"chat\" ? selection.model : undefined;\n\tconst primaryBudget = resolvePlannerRequest(primaryModel ?? model, request.thinkingLevel);\n\tconst primaryAuth = primaryModel\n\t\t? await resolvePlannerAuth(resolveAuth, primaryModel)\n\t\t: {\n\t\t\t\tfailure: {\n\t\t\t\t\tkind: \"providerError\" as const,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\tbackendFailure?.kind === \"providerError\"\n\t\t\t\t\t\t\t? backendFailure.message\n\t\t\t\t\t\t\t: `Compaction backend ${selection.kind} is not yet available`,\n\t\t\t\t},\n\t\t\t};\n\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tlet lastTerminal: TerminalPlannerOutcome | undefined = \"failure\" in primaryAuth ? primaryAuth.failure : undefined;\n\tlet borrowed = primaryModel !== model;\n\tlet planner: BorrowedPlanner | undefined;\n\n\tif (primaryModel && \"auth\" in primaryAuth) {\n\t\tplanner = { model: primaryModel, budget: primaryBudget, auth: primaryAuth.auth };\n\t} else {\n\t\tif (primaryModel) attempted.add(plannerAttemptKey({ model: primaryModel, budget: primaryBudget, auth: {} }));\n\t\tplanner = borrow && !timeLimit.expired() ? await borrow(attempted, resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\twhile (planner && !timeLimit.expired()) {\n\t\tlet attempt: PlannerAttempt;\n\t\ttry {\n\t\t\tattempt = await planWithTrimming(preparation, planner, plannerOptions);\n\t\t} catch (error) {\n\t\t\t// The time limit aborted the in-flight request: end planning, not the run.\n\t\t\tif (signal?.aborted || !timeLimit.expired()) throw error;\n\t\t\tbreak;\n\t\t}\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (attempt.kind === \"planned\") {\n\t\t\tconst plannerModel = borrowed ? borrowedIdentity(planner) : undefined;\n\t\t\tif (plannerModel) {\n\t\t\t\t// Best-effort: the durable entry already records the borrowed model;\n\t\t\t\t// a sidecar write failure never affects compaction success.\n\t\t\t\twriteSuccessDiagnosticSidecar({\n\t\t\t\t\tsessionFilePath: request.sessionFilePath,\n\t\t\t\t\tmodel: planner.model,\n\t\t\t\t\tsuccessCategory: \"borrowed_planner\",\n\t\t\t\t\t...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn plannedResult(\n\t\t\t\tpreparation,\n\t\t\t\tattempt.ranges,\n\t\t\t\tplannerModel,\n\t\t\t\tplannerUsage,\n\t\t\t\t`${planner.model.provider}/${planner.model.id}`,\n\t\t\t);\n\t\t}\n\t\tlastTerminal = attempt.outcome;\n\t\tif (attempt.outcome.kind === \"policyRefusal\" && request.summaryEntries) {\n\t\t\ttry {\n\t\t\t\tconst summary = await runPiSummaryFallback(request.summaryEntries, preparation.settings, planner, {\n\t\t\t\t\t...plannerOptions,\n\t\t\t\t\tcwd: request.cwd,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\ttext: summary.summary,\n\t\t\t\t\tranges: [],\n\t\t\t\t\tkeptRanges: [],\n\t\t\t\t\tstats: {\n\t\t\t\t\t\tlinesBefore: preparation.region.lines.length,\n\t\t\t\t\t\tlinesDeleted: 0,\n\t\t\t\t\t\tlinesKept: summary.summary.split(\"\\n\").length,\n\t\t\t\t\t\trangeCount: 0,\n\t\t\t\t\t\ttokensBefore: summary.tokensBefore,\n\t\t\t\t\t\ttokensAfter: summary.tokensAfter,\n\t\t\t\t\t\tpercentReduction:\n\t\t\t\t\t\t\tsummary.tokensBefore > 0 ? 100 * (1 - summary.tokensAfter / summary.tokensBefore) : 0,\n\t\t\t\t\t},\n\t\t\t\t\trung: \"planned\",\n\t\t\t\t\tkeptTail: true,\n\t\t\t\t\tbackend: \"summary\",\n\t\t\t\t\tmodel: `${planner.model.provider}/${planner.model.id}`,\n\t\t\t\t\tsummary: { readFiles: summary.readFiles, modifiedFiles: summary.modifiedFiles },\n\t\t\t\t\tsummaryFirstKeptEntryId: summary.firstKeptEntryId,\n\t\t\t\t\tsummaryTokensBefore: summary.tokensBefore,\n\t\t\t\t\t...(plannerUsage ? { usage: plannerUsage } : {}),\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\t\tlastTerminal = { kind: \"providerError\", message: error instanceof Error ? error.message : String(error) };\n\t\t\t}\n\t\t}\n\t\tattempted.add(plannerAttemptKey(planner));\n\t\tplanner = borrow && !timeLimit.expired() ? await borrow(attempted, resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\tif (timeLimit.expired()) lastTerminal = timeLimit.outcome;\n\tif (request.urgency !== \"load_bearing\") throw terminalError(lastTerminal);\n\treturn freshResult(preparation, hardInputLimit, plannerUsage, terminalMessage(lastTerminal));\n}\n"]}
@@ -128,6 +128,8 @@ export interface VerbatimCompactionDetails {
128
128
  tokensBefore?: number;
129
129
  /** Present only when a borrowed fallback model ranked the lines. */
130
130
  plannerModel?: CompactionPlannerModel;
131
+ /** Present only on a fresh rung reached after planning failed, e.g. `Compaction planning timed out after 300000 ms`. */
132
+ freshReason?: string;
131
133
  backupPath?: string;
132
134
  }
133
135
  export interface VerbatimCompactionPreparation {
@@ -156,6 +158,8 @@ export interface VerbatimCompactionResult {
156
158
  };
157
159
  /** Present only when a borrowed fallback model ranked the lines. */
158
160
  plannerModel?: CompactionPlannerModel;
161
+ /** Present only on a fresh rung reached after planning failed: why no planner could rank the lines. */
162
+ freshReason?: string;
159
163
  /** Aggregate usage across every planner request and retry in this compaction. */
160
164
  usage?: Usage;
161
165
  backupPath?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-types.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,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,CAAC,EAAE,MAAM,CAAC;IACtB,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,wHAAwH;IACxH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,6BAA6B;IAC7C,0FAA0F;IAC1F,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,MAAM,EAAE,cAAc,CAAC;IACvB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,4BAA4B,CAAC;IACzC,QAAQ,EAAE,kBAAkB,CAAC;CAC7B;AAED,MAAM,WAAW,wBAAwB;IACxC,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,uBAAuB,CAAC;IAC/B,UAAU,EAAE,4BAA4B,CAAC;IACzC,aAAa,EAAE,OAAO,kCAAkC,CAAC;IACzD,IAAI,EAAE,cAAc,CAAC;IACrB,OAAO,CAAC,EAAE,SAAS,GAAG,YAAY,GAAG,OAAO,GAAG,SAAS,CAAC;IACzD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,EAAE,CAAC;QAAC,aAAa,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IAC3D,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,uGAAuG;IACvG,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iFAAiF;IACjF,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-types.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAU,CAAC;AAC7D,MAAM,CAAC,MAAM,4BAA4B,GAAG,gBAAyB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { CompactionSettings } from \"./compaction.ts\";\n\nexport const VERBATIM_COMPACTION_PROMPT_VERSION = 4 as const;\nexport const VERBATIM_COMPACTION_STRATEGY = \"verbatim-lines\" as const;\n\nexport const DEFAULT_COMPRESSION_RATIO = 0.5;\nexport const DEFAULT_PRESERVE_RECENT = 2;\nexport const MIN_COMPACTABLE_REGION_LINES = 20;\n\nexport interface VerbatimCompactionParameters {\n\t/** Fraction of compactable region lines to keep. */\n\tcompression_ratio: number;\n\t/** Recent context-eligible messages retained outside the compactable region. */\n\tpreserve_recent: number;\n\t/** Relevance focus used by the range planner. */\n\tquery: string;\n}\n\nexport interface LineRange {\n\t/** One-based inclusive first line. */\n\tstart: number;\n\t/** One-based inclusive last line. */\n\tend: number;\n}\n\nexport type RawLineEndpoint = number | string | boolean | null;\n\nexport interface RawLineRange {\n\tstart?: RawLineEndpoint;\n\tend?: RawLineEndpoint;\n}\n\nexport interface NumberedRegion {\n\treadonly __brand: \"NumberedRegion\";\n\tlines: string[];\n\tmessageSpans?: { role: \"user\" | \"assistant\" | \"tool\"; start: number; end: number }[];\n\theaderLineNumbers: ReadonlySet<number>;\n\tpriorMarkerNs: ReadonlyMap<number, number>;\n\t/** Optional future protected spans, expressed as one-based line numbers. */\n\tprotectedLineNumbers?: ReadonlySet<number>;\n\ttokenEstimate: number;\n}\n\nexport type ValidatedRanges = readonly LineRange[] & { readonly __brand: \"ValidatedRanges\" };\n\nexport interface CompactedTranscript {\n\ttext: string;\n\tranges: LineRange[];\n\t/**\n\t * Ranges force-preserved by `<keepContext>` protection; empty when nothing was protected.\n\t * Reported so protection that fired unexpectedly — a transcript that quotes tag text, say —\n\t * is diagnosable rather than a silent reduction in what compaction reclaimed.\n\t */\n\tkeptRanges: LineRange[];\n\tstats: VerbatimCompactionStats;\n}\n\nexport interface VerbatimCompactionStats {\n\tlinesBefore: number;\n\tlinesDeleted: number;\n\tlinesKept: number;\n\trangeCount: number;\n\ttokensBefore: number;\n\ttokensAfter: number;\n\tpercentReduction: number;\n}\n\n/** How much the caller can afford to lose if compaction does not happen. */\nexport type CompactionUrgency =\n\t/** Manual /compact, threshold auto-compaction — failing is safe. */\n\t| \"recoverable\"\n\t/** Overflow recovery, post-tool preflight — failing kills the turn. */\n\t| \"load_bearing\";\n\n/** How a durable compaction boundary was produced. */\nexport type CompactionRung = \"planned\" | \"extension\" | \"fresh\";\n\n/** Credentials for one planner request. Resolved per model, never shared. */\nexport interface PlannerAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * What one planner request may spend.\n *\n * `maxTokens` is declared `undefined`, not `number | undefined`: the type\n * forbids reintroducing the `0.8 * reserveTokens` output cap without changing\n * the type and failing review. pi-ai's `clampMaxTokensToContext` is the only bound.\n */\nexport interface PlannerBudget {\n\treadonly maxTokens: undefined;\n\treadonly reasoning: ThinkingLevel | undefined;\n}\n\n/**\n * A planner-only model borrowing. Cannot be confused with a session model switch.\n *\n * It carries no attempted-set key: the effective identity of an attempt is\n * `provider/model:<effective reasoning>`, derived from `model` and\n * `budget.reasoning` by `plannerAttemptKey`. Storing a key resolved from the raw\n * optional suffix would let the same effective request run twice.\n */\nexport interface BorrowedPlanner {\n\treadonly model: Model<Api>;\n\treadonly budget: PlannerBudget;\n\treadonly auth: PlannerAuth;\n}\n\n/** Identity of the model that ranked the deleted lines, when it was borrowed. */\nexport interface CompactionPlannerModel {\n\tprovider: string;\n\tid: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport interface VerbatimCompactionDetails {\n\tstrategy: typeof VERBATIM_COMPACTION_STRATEGY;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\tparameters: VerbatimCompactionParameters;\n\tstats: VerbatimCompactionStats;\n\trung: CompactionRung;\n\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t/**\n\t * Authoritative whole-context count, projected for display only. Populated by\n\t * `createVerbatimCompactionMessage` on the rendered message; it is not\n\t * persisted here — the durable entry already carries it as\n\t * `CompactionEntry.tokensBefore`.\n\t */\n\ttokensBefore?: number;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\tbackupPath?: string;\n}\n\nexport interface VerbatimCompactionPreparation {\n\t/** First context-visible tail entry, or null when no pre-boundary message is retained. */\n\tfirstKeptEntryId: string | null;\n\tregion: NumberedRegion;\n\tregionEntryIds: string[];\n\tkeptTailMessageCount: number;\n\ttokensBefore: number;\n\tparameters: VerbatimCompactionParameters;\n\tsettings: CompactionSettings;\n}\n\nexport interface VerbatimCompactionResult {\n\tcompactedText: string;\n\tfirstKeptEntryId: string | null;\n\ttokensBefore: number;\n\tstats: VerbatimCompactionStats;\n\tparameters: VerbatimCompactionParameters;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\trung: CompactionRung;\n\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** Aggregate usage across every planner request and retry in this compaction. */\n\tusage?: Usage;\n\tbackupPath?: string;\n}\n"]}
1
+ {"version":3,"file":"compaction-types.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAU,CAAC;AAC7D,MAAM,CAAC,MAAM,4BAA4B,GAAG,gBAAyB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, Model, Usage } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { CompactionSettings } from \"./compaction.ts\";\n\nexport const VERBATIM_COMPACTION_PROMPT_VERSION = 4 as const;\nexport const VERBATIM_COMPACTION_STRATEGY = \"verbatim-lines\" as const;\n\nexport const DEFAULT_COMPRESSION_RATIO = 0.5;\nexport const DEFAULT_PRESERVE_RECENT = 2;\nexport const MIN_COMPACTABLE_REGION_LINES = 20;\n\nexport interface VerbatimCompactionParameters {\n\t/** Fraction of compactable region lines to keep. */\n\tcompression_ratio: number;\n\t/** Recent context-eligible messages retained outside the compactable region. */\n\tpreserve_recent: number;\n\t/** Relevance focus used by the range planner. */\n\tquery: string;\n}\n\nexport interface LineRange {\n\t/** One-based inclusive first line. */\n\tstart: number;\n\t/** One-based inclusive last line. */\n\tend: number;\n}\n\nexport type RawLineEndpoint = number | string | boolean | null;\n\nexport interface RawLineRange {\n\tstart?: RawLineEndpoint;\n\tend?: RawLineEndpoint;\n}\n\nexport interface NumberedRegion {\n\treadonly __brand: \"NumberedRegion\";\n\tlines: string[];\n\tmessageSpans?: { role: \"user\" | \"assistant\" | \"tool\"; start: number; end: number }[];\n\theaderLineNumbers: ReadonlySet<number>;\n\tpriorMarkerNs: ReadonlyMap<number, number>;\n\t/** Optional future protected spans, expressed as one-based line numbers. */\n\tprotectedLineNumbers?: ReadonlySet<number>;\n\ttokenEstimate: number;\n}\n\nexport type ValidatedRanges = readonly LineRange[] & { readonly __brand: \"ValidatedRanges\" };\n\nexport interface CompactedTranscript {\n\ttext: string;\n\tranges: LineRange[];\n\t/**\n\t * Ranges force-preserved by `<keepContext>` protection; empty when nothing was protected.\n\t * Reported so protection that fired unexpectedly — a transcript that quotes tag text, say —\n\t * is diagnosable rather than a silent reduction in what compaction reclaimed.\n\t */\n\tkeptRanges: LineRange[];\n\tstats: VerbatimCompactionStats;\n}\n\nexport interface VerbatimCompactionStats {\n\tlinesBefore: number;\n\tlinesDeleted: number;\n\tlinesKept: number;\n\trangeCount: number;\n\ttokensBefore: number;\n\ttokensAfter: number;\n\tpercentReduction: number;\n}\n\n/** How much the caller can afford to lose if compaction does not happen. */\nexport type CompactionUrgency =\n\t/** Manual /compact, threshold auto-compaction — failing is safe. */\n\t| \"recoverable\"\n\t/** Overflow recovery, post-tool preflight — failing kills the turn. */\n\t| \"load_bearing\";\n\n/** How a durable compaction boundary was produced. */\nexport type CompactionRung = \"planned\" | \"extension\" | \"fresh\";\n\n/** Credentials for one planner request. Resolved per model, never shared. */\nexport interface PlannerAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * What one planner request may spend.\n *\n * `maxTokens` is declared `undefined`, not `number | undefined`: the type\n * forbids reintroducing the `0.8 * reserveTokens` output cap without changing\n * the type and failing review. pi-ai's `clampMaxTokensToContext` is the only bound.\n */\nexport interface PlannerBudget {\n\treadonly maxTokens: undefined;\n\treadonly reasoning: ThinkingLevel | undefined;\n}\n\n/**\n * A planner-only model borrowing. Cannot be confused with a session model switch.\n *\n * It carries no attempted-set key: the effective identity of an attempt is\n * `provider/model:<effective reasoning>`, derived from `model` and\n * `budget.reasoning` by `plannerAttemptKey`. Storing a key resolved from the raw\n * optional suffix would let the same effective request run twice.\n */\nexport interface BorrowedPlanner {\n\treadonly model: Model<Api>;\n\treadonly budget: PlannerBudget;\n\treadonly auth: PlannerAuth;\n}\n\n/** Identity of the model that ranked the deleted lines, when it was borrowed. */\nexport interface CompactionPlannerModel {\n\tprovider: string;\n\tid: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport interface VerbatimCompactionDetails {\n\tstrategy: typeof VERBATIM_COMPACTION_STRATEGY;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\tparameters: VerbatimCompactionParameters;\n\tstats: VerbatimCompactionStats;\n\trung: CompactionRung;\n\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t/**\n\t * Authoritative whole-context count, projected for display only. Populated by\n\t * `createVerbatimCompactionMessage` on the rendered message; it is not\n\t * persisted here — the durable entry already carries it as\n\t * `CompactionEntry.tokensBefore`.\n\t */\n\ttokensBefore?: number;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** Present only on a fresh rung reached after planning failed, e.g. `Compaction planning timed out after 300000 ms`. */\n\tfreshReason?: string;\n\tbackupPath?: string;\n}\n\nexport interface VerbatimCompactionPreparation {\n\t/** First context-visible tail entry, or null when no pre-boundary message is retained. */\n\tfirstKeptEntryId: string | null;\n\tregion: NumberedRegion;\n\tregionEntryIds: string[];\n\tkeptTailMessageCount: number;\n\ttokensBefore: number;\n\tparameters: VerbatimCompactionParameters;\n\tsettings: CompactionSettings;\n}\n\nexport interface VerbatimCompactionResult {\n\tcompactedText: string;\n\tfirstKeptEntryId: string | null;\n\ttokensBefore: number;\n\tstats: VerbatimCompactionStats;\n\tparameters: VerbatimCompactionParameters;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\trung: CompactionRung;\n\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\tmodel?: string;\n\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** Present only on a fresh rung reached after planning failed: why no planner could rank the lines. */\n\tfreshReason?: string;\n\t/** Aggregate usage across every planner request and retry in this compaction. */\n\tusage?: Usage;\n\tbackupPath?: string;\n}\n"]}
@@ -9,6 +9,8 @@ export declare const SETTINGS_DEFAULTS: {
9
9
  readonly reserveTokens: 16384;
10
10
  readonly compression_ratio: 0.5;
11
11
  readonly preserve_recent: 2;
12
+ /** Wall-clock limit on automatic compaction's model planning, so it cannot block a turn (#4198). */
13
+ readonly planningTimeoutMs: 300000;
12
14
  };
13
15
  readonly branchSummary: {
14
16
  readonly reserveTokens: 16384;
@@ -1 +1 @@
1
- {"version":3,"file":"settings-defaults.d.ts","sourceRoot":"","sources":["../../src/core/settings-defaults.ts"],"names":[],"mappings":"AAEA,mFAAmF;AACnF,eAAO,MAAM,iBAAiB;aAC7B,WAAW,EAAE,EAAE;aACf,SAAS,EAAE,MAAM;aACjB,YAAY,EAAE,eAAe;aAC7B,YAAY,EAAE,eAAe;aAC7B,UAAU;iBACT,OAAO;iBACP,aAAa,EAAE,KAAK;iBACpB,iBAAiB,EAAE,GAAG;iBACtB,eAAe,EAAE,CAAC;;aAEnB,aAAa;iBACZ,aAAa,EAAE,KAAK;iBACpB,UAAU;;aAEX,cAAc;iBACb,OAAO;;aAER,KAAK;iBACJ,OAAO;iBACP,UAAU,EAAE,CAAC;iBACb,WAAW,EAAE,IAAI;iBACjB,eAAe;iBACf,uBAAuB;iBACvB,QAAQ;qBACP,eAAe,EAAE,KAAK;;;aAGxB,iBAAiB;aACjB,oBAAoB;aACpB,YAAY;aACZ,mBAAmB,EAAE,KAAK;aAC1B,eAAe;iBACd,OAAO;;aAER,MAAM;iBACL,aAAa,EAAE,CAAC;iBAChB,YAAY,EAAE,CAAC;;aAEhB,iBAAiB;aACjB,sBAAsB;aACtB,mBAAmB;aACnB,KAAK;iBACJ,OAAO;;aAER,QAAQ;iBACP,UAAU;iBACV,eAAe,EAAE,EAAE;iBACnB,aAAa;iBACb,oBAAoB;;aAErB,MAAM;iBACL,UAAU;iBACV,WAAW;;aAEZ,kBAAkB,EAAE,MAAM;aAC1B,cAAc,EAAE,SAAS;aACzB,cAAc,EAAE,CAAC;aACjB,SAAS,EAAE,CAAC;aACZ,sBAAsB,EAAE,CAAC;aACzB,mBAAmB,EAAE,MAAM;aAC3B,oBAAoB,EAAE,YAAY;aAClC,sBAAsB;aACtB,0BAA0B,EAAE,MAAM;aAClC,QAAQ;iBACP,IAAI,EAAE,IAAI;iBACV,YAAY,EAAE,IAAI;;aAEnB,QAAQ;iBACP,eAAe,EAAE,IAAI;iBACrB,OAAO,EAAE,WAAW;iBACpB,KAAK;;aAEN,QAAQ;iBACP,mBAAmB;;aAEpB,iBAAiB,EAAE,MAAO;aAC1B,YAAY,EAAE,WAAW;aACzB,KAAK;QACJ,qDAAqD;iBACrD,WAAW;;CAEH,CAAC"}
1
+ {"version":3,"file":"settings-defaults.d.ts","sourceRoot":"","sources":["../../src/core/settings-defaults.ts"],"names":[],"mappings":"AAEA,mFAAmF;AACnF,eAAO,MAAM,iBAAiB;aAC7B,WAAW,EAAE,EAAE;aACf,SAAS,EAAE,MAAM;aACjB,YAAY,EAAE,eAAe;aAC7B,YAAY,EAAE,eAAe;aAC7B,UAAU;iBACT,OAAO;iBACP,aAAa,EAAE,KAAK;iBACpB,iBAAiB,EAAE,GAAG;iBACtB,eAAe,EAAE,CAAC;QAClB,oGAAoG;iBACpG,iBAAiB,EAAE,MAAO;;aAE3B,aAAa;iBACZ,aAAa,EAAE,KAAK;iBACpB,UAAU;;aAEX,cAAc;iBACb,OAAO;;aAER,KAAK;iBACJ,OAAO;iBACP,UAAU,EAAE,CAAC;iBACb,WAAW,EAAE,IAAI;iBACjB,eAAe;iBACf,uBAAuB;iBACvB,QAAQ;qBACP,eAAe,EAAE,KAAK;;;aAGxB,iBAAiB;aACjB,oBAAoB;aACpB,YAAY;aACZ,mBAAmB,EAAE,KAAK;aAC1B,eAAe;iBACd,OAAO;;aAER,MAAM;iBACL,aAAa,EAAE,CAAC;iBAChB,YAAY,EAAE,CAAC;;aAEhB,iBAAiB;aACjB,sBAAsB;aACtB,mBAAmB;aACnB,KAAK;iBACJ,OAAO;;aAER,QAAQ;iBACP,UAAU;iBACV,eAAe,EAAE,EAAE;iBACnB,aAAa;iBACb,oBAAoB;;aAErB,MAAM;iBACL,UAAU;iBACV,WAAW;;aAEZ,kBAAkB,EAAE,MAAM;aAC1B,cAAc,EAAE,SAAS;aACzB,cAAc,EAAE,CAAC;aACjB,SAAS,EAAE,CAAC;aACZ,sBAAsB,EAAE,CAAC;aACzB,mBAAmB,EAAE,MAAM;aAC3B,oBAAoB,EAAE,YAAY;aAClC,sBAAsB;aACtB,0BAA0B,EAAE,MAAM;aAClC,QAAQ;iBACP,IAAI,EAAE,IAAI;iBACV,YAAY,EAAE,IAAI;;aAEnB,QAAQ;iBACP,eAAe,EAAE,IAAI;iBACrB,OAAO,EAAE,WAAW;iBACpB,KAAK;;aAEN,QAAQ;iBACP,mBAAmB;;aAEpB,iBAAiB,EAAE,MAAO;aAC1B,YAAY,EAAE,WAAW;aACzB,KAAK;QACJ,qDAAqD;iBACrD,WAAW;;CAEH,CAAC"}
@@ -10,6 +10,8 @@ export const SETTINGS_DEFAULTS = {
10
10
  reserveTokens: 16384,
11
11
  compression_ratio: 0.5,
12
12
  preserve_recent: 2,
13
+ /** Wall-clock limit on automatic compaction's model planning, so it cannot block a turn (#4198). */
14
+ planningTimeoutMs: 300_000,
13
15
  },
14
16
  branchSummary: {
15
17
  reserveTokens: 16384,
@@ -1 +1 @@
1
- {"version":3,"file":"settings-defaults.js","sourceRoot":"","sources":["../../src/core/settings-defaults.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4BAA4B,CAAC;AAE9E,mFAAmF;AACnF,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAChC,WAAW,EAAE,EAAE;IACf,SAAS,EAAE,MAAM;IACjB,Y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AE,MAAM;IAClC,QAAQ,EAAE;QACT,IAAI,EAAE,IAAI;QACV,YAAY,EAAE,IAAI;KAClB;IACD,QAAQ,EAAE;QACT,eAAe,EAAE,IAAI;QACrB,OAAO,EAAE,WAAW;QACpB,KAAK,EAAE,IAAI;KACX;IACD,QAAQ,EAAE;QACT,mBAAmB,EAAE,IAAI;KACzB;IACD,iBAAiB,EAAE,OAAO;IAC1B,YAAY,EAAE,WAAW;IACzB,KAAK,EAAE;QACN,qDAAqD;QACrD,WAAW,EAAE,EAAE,GAAG,MAAM;KACxB;CACQ,CAAC","sourcesContent":["import { DEFAULT_MAX_AGENT_RETRY_DELAY_MS } from \"@bastani/pi-ai/utils/retry\";\n\n/** Runtime defaults shared by settings accessors and the published JSON Schema. */\nexport const SETTINGS_DEFAULTS = {\n\trouterModel: \"\",\n\ttransport: \"auto\",\n\tsteeringMode: \"one-at-a-time\",\n\tfollowUpMode: \"one-at-a-time\",\n\tcompaction: {\n\t\tenabled: true,\n\t\treserveTokens: 16384,\n\t\tcompression_ratio: 0.5,\n\t\tpreserve_recent: 2,\n\t},\n\tbranchSummary: {\n\t\treserveTokens: 16384,\n\t\tskipPrompt: false,\n\t},\n\tsessionSummary: {\n\t\tenabled: true,\n\t},\n\tretry: {\n\t\tenabled: true,\n\t\tmaxRetries: 3,\n\t\tbaseDelayMs: 2000,\n\t\tmaxAgentDelayMs: DEFAULT_MAX_AGENT_RETRY_DELAY_MS,\n\t\tfallbackOnContentFilter: true,\n\t\tprovider: {\n\t\t\tmaxRetryDelayMs: 60000,\n\t\t},\n\t},\n\thideThinkingBlock: false,\n\tshowCacheMissNotices: false,\n\tquietStartup: false,\n\tdefaultProjectTrust: \"ask\",\n\tbashInterceptor: {\n\t\tenabled: false,\n\t},\n\tsearch: {\n\t\tcontextBefore: 1,\n\t\tcontextAfter: 3,\n\t},\n\tcollapseChangelog: false,\n\tenableInstallTelemetry: true,\n\tenableSkillCommands: true,\n\therdr: {\n\t\tenabled: true,\n\t},\n\tterminal: {\n\t\tshowImages: true,\n\t\timageWidthCells: 60,\n\t\tclearOnShrink: false,\n\t\tshowTerminalProgress: false,\n\t},\n\timages: {\n\t\tautoResize: true,\n\t\tblockImages: false,\n\t},\n\tdoubleEscapeAction: \"tree\",\n\ttreeFilterMode: \"default\",\n\teditorPaddingX: 0,\n\toutputPad: 1,\n\tautocompleteMaxVisible: 5,\n\tfullscreenScrollbar: \"auto\",\n\tfullscreenExitOutput: \"transcript\",\n\tfullscreenCopyOnSelect: true,\n\tfullscreenWheelScrollLines: \"auto\",\n\tcodemode: {\n\t\tmode: \"on\",\n\t\tinlineBudget: 3000,\n\t},\n\tmarkdown: {\n\t\tcodeBlockIndent: \" \",\n\t\tmermaid: \"streaming\",\n\t\tlatex: true,\n\t},\n\twarnings: {\n\t\tanthropicExtraUsage: true,\n\t},\n\thttpIdleTimeoutMs: 600_000,\n\tcacheWarming: \"streaming\",\n\ttasks: {\n\t\t/** Same 15-minute default as workflow heartbeats. */\n\t\theartbeatMs: 15 * 60_000,\n\t},\n} as const;\n"]}
1
+ {"version":3,"file":"settings-defaults.js","sourceRoot":"","sources":["../../src/core/settings-defaults.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4BAA4B,CAAC;AAE9E,mFAAmF;AACnF,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAChC,WAAW,EAAE,EAAE;IACf,SAAS,EAAE,MAAM;IACjB,YAAY,EAAE,eAAe;IAC7B,YAAY,EAAE,eAAe;IAC7B,UAAU,EAAE;QACX,OAAO,EAAE,IAAI;QACb,aAAa,EAAE,KAAK;QACpB,iBAAiB,EAAE,GAAG;QACtB,eAAe,EAAE,CAAC;QAClB,oGAAoG;QACpG,iBAAiB,EAAE,OAAO;KAC1B;IACD,aAAa,EAAE;QACd,aAAa,EAAE,KAAK;QACpB,UAAU,EAAE,KAAK;KACjB;IACD,cAAc,EAAE;QACf,OAAO,EAAE,IAAI;KACb;IACD,KAAK,EAAE;Q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,qDAAqD;QACrD,WAAW,EAAE,EAAE,GAAG,MAAM;KACxB;CACQ,CAAC","sourcesContent":["import { DEFAULT_MAX_AGENT_RETRY_DELAY_MS } from \"@bastani/pi-ai/utils/retry\";\n\n/** Runtime defaults shared by settings accessors and the published JSON Schema. */\nexport const SETTINGS_DEFAULTS = {\n\trouterModel: \"\",\n\ttransport: \"auto\",\n\tsteeringMode: \"one-at-a-time\",\n\tfollowUpMode: \"one-at-a-time\",\n\tcompaction: {\n\t\tenabled: true,\n\t\treserveTokens: 16384,\n\t\tcompression_ratio: 0.5,\n\t\tpreserve_recent: 2,\n\t\t/** Wall-clock limit on automatic compaction's model planning, so it cannot block a turn (#4198). */\n\t\tplanningTimeoutMs: 300_000,\n\t},\n\tbranchSummary: {\n\t\treserveTokens: 16384,\n\t\tskipPrompt: false,\n\t},\n\tsessionSummary: {\n\t\tenabled: true,\n\t},\n\tretry: {\n\t\tenabled: true,\n\t\tmaxRetries: 3,\n\t\tbaseDelayMs: 2000,\n\t\tmaxAgentDelayMs: DEFAULT_MAX_AGENT_RETRY_DELAY_MS,\n\t\tfallbackOnContentFilter: true,\n\t\tprovider: {\n\t\t\tmaxRetryDelayMs: 60000,\n\t\t},\n\t},\n\thideThinkingBlock: false,\n\tshowCacheMissNotices: false,\n\tquietStartup: false,\n\tdefaultProjectTrust: \"ask\",\n\tbashInterceptor: {\n\t\tenabled: false,\n\t},\n\tsearch: {\n\t\tcontextBefore: 1,\n\t\tcontextAfter: 3,\n\t},\n\tcollapseChangelog: false,\n\tenableInstallTelemetry: true,\n\tenableSkillCommands: true,\n\therdr: {\n\t\tenabled: true,\n\t},\n\tterminal: {\n\t\tshowImages: true,\n\t\timageWidthCells: 60,\n\t\tclearOnShrink: false,\n\t\tshowTerminalProgress: false,\n\t},\n\timages: {\n\t\tautoResize: true,\n\t\tblockImages: false,\n\t},\n\tdoubleEscapeAction: \"tree\",\n\ttreeFilterMode: \"default\",\n\teditorPaddingX: 0,\n\toutputPad: 1,\n\tautocompleteMaxVisible: 5,\n\tfullscreenScrollbar: \"auto\",\n\tfullscreenExitOutput: \"transcript\",\n\tfullscreenCopyOnSelect: true,\n\tfullscreenWheelScrollLines: \"auto\",\n\tcodemode: {\n\t\tmode: \"on\",\n\t\tinlineBudget: 3000,\n\t},\n\tmarkdown: {\n\t\tcodeBlockIndent: \" \",\n\t\tmermaid: \"streaming\",\n\t\tlatex: true,\n\t},\n\twarnings: {\n\t\tanthropicExtraUsage: true,\n\t},\n\thttpIdleTimeoutMs: 600_000,\n\tcacheWarming: \"streaming\",\n\ttasks: {\n\t\t/** Same 15-minute default as workflow heartbeats. */\n\t\theartbeatMs: 15 * 60_000,\n\t},\n} as const;\n"]}
@@ -56,6 +56,8 @@ interface SettingsManagerBasicAccessors {
56
56
  getCompactionCompressionRatio(): number;
57
57
  getCompactionPreserveRecent(model?: CompactionModel): number;
58
58
  getCompactionQuery(): string | undefined;
59
+ /** Wall-clock limit on automatic compaction's model planning; `undefined` when disabled. */
60
+ getCompactionPlanningTimeoutMs(): number | undefined;
59
61
  getCompactionSettings(model?: CompactionModel): {
60
62
  enabled: boolean;
61
63
  reserveTokens: number;
@@ -1 +1 @@
1
- {"version":3,"file":"settings-manager-basic-accessors.d.ts","sourceRoot":"","sources":["../../src/core/settings-manager-basic-accessors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,KAAK,EAAuB,MAAM,gBAAgB,CAAC;AAMjE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,KAAK,EAGX,oBAAoB,EACpB,gBAAgB,EAChB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAuB,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEjF,KAAK,eAAe,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC,CAAC;AA6C9D,UAAU,6BAA6B;IACtC,mBAAmB,IAAI,gBAAgB,CAAC;IAC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AW,EAAE,MAAM,CAAC;QACpB,eAAe,EAAE,MAAM,CAAC;QACxB,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,uBAAuB,EAAE,OAAO,CAAC;KACjC,CAAC;IACF,YAAY,IAAI,MAAM,GAAG,SAAS,CAAC;IACnC,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAAC;IAC9C,oBAAoB,IAAI,MAAM,CAAC;IAC/B,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9C,4BAA4B,IAAI,MAAM,GAAG,SAAS,CAAC;IACnD,mBAAmB,IAAI,MAAM,GAAG,SAAS,CAAC;IAC1C,wBAAwB,IAAI;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,eAAe,EAAE,MAAM,CAAA;KAAE,CAAC;CACjG;AAED,OAAO,QAAQ,4BAA4B,CAAC;IAC3C,UAAU,eAAgB,SAAQ,6BAA6B;KAAG;CAClE"}
1
+ {"version":3,"file":"settings-manager-basic-accessors.d.ts","sourceRoot":"","sources":["../../src/core/settings-manager-basic-accessors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,KAAK,EAAuB,MAAM,gBAAgB,CAAC;AAMjE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,KAAK,EAGX,oBAAoB,EACpB,gBAAgB,EAChB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAuB,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEjF,KAAK,eAAe,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC,CAAC;AA6C9D,UAAU,6BAA6B;IACtC,mBAAmB,IAAI,gBAAgB,CAAC;IACxC,mBAAmB,CAAC,IAAI,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAClD,uBAAuB,IAAI,MAAM,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ACpB,eAAe,EAAE,MAAM,CAAC;QACxB,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,uBAAuB,EAAE,OAAO,CAAC;KACjC,CAAC;IACF,YAAY,IAAI,MAAM,GAAG,SAAS,CAAC;IACnC,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAAC;IAC9C,oBAAoB,IAAI,MAAM,CAAC;IAC/B,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9C,4BAA4B,IAAI,MAAM,GAAG,SAAS,CAAC;IACnD,mBAAmB,IAAI,MAAM,GAAG,SAAS,CAAC;IAC1C,wBAAwB,IAAI;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,eAAe,EAAE,MAAM,CAAA;KAAE,CAAC;CACjG;AAED,OAAO,QAAQ,4BAA4B,CAAC;IAC3C,UAAU,eAAgB,SAAQ,6BAA6B;KAAG;CAClE"}
@@ -337,6 +337,13 @@ const basicAccessors = {
337
337
  const query = settingsInternals(this).settings.compaction?.query?.trim();
338
338
  return query && query.length > 0 ? query : undefined;
339
339
  },
340
+ getCompactionPlanningTimeoutMs() {
341
+ const raw = settingsInternals(this).settings.compaction?.planningTimeoutMs;
342
+ // A positive fraction of a millisecond is still a limit: only 0 or "disabled" turn it off.
343
+ const configured = typeof raw === "number" && raw > 0 && raw < 1 ? 1 : parseHttpIdleTimeoutMs(raw);
344
+ const timeoutMs = configured ?? SETTINGS_DEFAULTS.compaction.planningTimeoutMs;
345
+ return timeoutMs > 0 ? timeoutMs : undefined;
346
+ },
340
347
  getCompactionSettings(model) {
341
348
  const query = this.getCompactionQuery();
342
349
  return {