opencode-acp 1.18.4 → 1.18.5-pr.408.227

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -921,6 +921,7 @@ var VALID_CONFIG_KEYS = /* @__PURE__ */ new Set([
921
921
  "compress.images.minBytes",
922
922
  "compress.images.ttlDays",
923
923
  "compress.completionReserveTokens",
924
+ "compress.emergencyTruncation",
924
925
  "gc",
925
926
  "gc.algorithm",
926
927
  "gc.promotionThreshold",
@@ -1350,6 +1351,13 @@ function validateConfigTypes(config) {
1350
1351
  actual: typeof compress.completionReserveTokens
1351
1352
  });
1352
1353
  }
1354
+ if (compress.emergencyTruncation !== void 0 && typeof compress.emergencyTruncation !== "boolean") {
1355
+ errors.push({
1356
+ key: "compress.emergencyTruncation",
1357
+ expected: "boolean",
1358
+ actual: typeof compress.emergencyTruncation
1359
+ });
1360
+ }
1353
1361
  if (typeof compress.completionReserveTokens === "number" && compress.completionReserveTokens < 0) {
1354
1362
  errors.push({
1355
1363
  key: "compress.completionReserveTokens",
@@ -1422,6 +1430,7 @@ function validateConfigTypes(config) {
1422
1430
  const OVERRIDE_FIELD_TYPES = {
1423
1431
  showCompression: "boolean",
1424
1432
  summaryBuffer: "boolean",
1433
+ emergencyTruncation: "boolean",
1425
1434
  protectTags: "boolean",
1426
1435
  protectUserMessages: "boolean",
1427
1436
  lastSegmentSoftBlock: "boolean",
@@ -1809,6 +1818,7 @@ var defaultConfig = {
1809
1818
  permission: "allow",
1810
1819
  showCompression: true,
1811
1820
  summaryBuffer: true,
1821
+ emergencyTruncation: false,
1812
1822
  candidates: false,
1813
1823
  maxContextLimit: "80%",
1814
1824
  minContextLimit: "80%",
@@ -2017,7 +2027,8 @@ function mergeCompress(base, override) {
2017
2027
  minBytes: override.images?.minBytes ?? base.images?.minBytes ?? DEFAULT_COMPRESS_IMAGES.minBytes,
2018
2028
  ttlDays: override.images?.ttlDays ?? base.images?.ttlDays ?? DEFAULT_COMPRESS_IMAGES.ttlDays
2019
2029
  },
2020
- completionReserveTokens: override.completionReserveTokens ?? base.completionReserveTokens
2030
+ completionReserveTokens: override.completionReserveTokens ?? base.completionReserveTokens,
2031
+ emergencyTruncation: override.emergencyTruncation ?? base.emergencyTruncation
2021
2032
  };
2022
2033
  }
2023
2034
  function mergeCommands(base, override) {
@@ -2955,7 +2966,8 @@ function saveSessionState(sessionState, logger, sessionName) {
2955
2966
  modelContextLimit: sessionState.modelContextLimit,
2956
2967
  modelProviderID: sessionState.modelProviderID,
2957
2968
  modelID: sessionState.modelID,
2958
- imageArchive: sessionState.imageArchive
2969
+ imageArchive: sessionState.imageArchive,
2970
+ stickyTruncations: sessionState.stickyTruncations
2959
2971
  };
2960
2972
  const key = saveQueueKey(sessionState.sessionId, sessionState.storageDir);
2961
2973
  let queue = saveQueues.get(key);
@@ -4978,6 +4990,30 @@ async function updatePerTurnState(state, logger, messages) {
4978
4990
  state.currentTurn = countTurns(state, messages);
4979
4991
  }
4980
4992
  var REGISTRY_SOFT_CAP = 32;
4993
+ function createSessionGuard() {
4994
+ const locks = /* @__PURE__ */ new Map();
4995
+ return async (sessionId, fn) => {
4996
+ const previous = locks.get(sessionId) ?? Promise.resolve();
4997
+ let release;
4998
+ const released = new Promise((resolve2) => {
4999
+ release = resolve2;
5000
+ });
5001
+ const chain = previous.then(() => released);
5002
+ locks.set(sessionId, chain);
5003
+ try {
5004
+ await previous;
5005
+ } catch {
5006
+ }
5007
+ try {
5008
+ return await fn();
5009
+ } finally {
5010
+ release();
5011
+ if (locks.get(sessionId) === chain) {
5012
+ locks.delete(sessionId);
5013
+ }
5014
+ }
5015
+ };
5016
+ }
4981
5017
  var SessionStateRegistry = class {
4982
5018
  constructor(logger, projectDir) {
4983
5019
  this.logger = logger;
@@ -5037,9 +5073,17 @@ var SessionStateRegistry = class {
5037
5073
  get size() {
5038
5074
  return this.states.size;
5039
5075
  }
5076
+ // [Issue #404] Per-session FIFO mutex serializing same-session mutations
5077
+ // (message transforms, compress/decompress tools, event-hook saves,
5078
+ // system-hook limit writes). Shared factory so test stubs compose the
5079
+ // exact same implementation instead of drifting.
5080
+ // Not readonly: the session-guard wiring test wraps this to observe
5081
+ // acquisition order (Issue #404).
5082
+ withSessionGuard = createSessionGuard();
5040
5083
  // Idempotent: ensureSessionInitialized returns immediately once
5041
- // state.sessionId === sessionId (assigned synchronously before any await),
5042
- // so repeat calls for the same session never re-reset.
5084
+ // state.sessionId === sessionId, and coalesces concurrent inits per state
5085
+ // object ([Issue #404]), so racing calls for the same session never
5086
+ // re-reset or observe partially initialized state.
5043
5087
  async getOrCreate(client, sessionId, messages, config) {
5044
5088
  let state = this.states.get(sessionId);
5045
5089
  if (!state) {
@@ -5124,7 +5168,8 @@ function createSessionState() {
5124
5168
  qualityGateRetryPending: false,
5125
5169
  noContextLimitWarned: false,
5126
5170
  imageArchive: {},
5127
- imagePruneDone: false
5171
+ imagePruneDone: false,
5172
+ stickyTruncations: {}
5128
5173
  };
5129
5174
  }
5130
5175
  function resetSessionState(state) {
@@ -5170,11 +5215,35 @@ function resetSessionState(state) {
5170
5215
  state.noContextLimitWarned = false;
5171
5216
  state.imageArchive = {};
5172
5217
  state.imagePruneDone = false;
5218
+ state.stickyTruncations = {};
5173
5219
  }
5220
+ var inflightInits = /* @__PURE__ */ new WeakMap();
5174
5221
  async function ensureSessionInitialized(client, state, sessionId, logger, messages, config, projectDir) {
5222
+ const inflight = inflightInits.get(state);
5223
+ if (inflight) {
5224
+ await inflight;
5225
+ return;
5226
+ }
5175
5227
  if (state.sessionId === sessionId) {
5176
5228
  return;
5177
5229
  }
5230
+ const run = runSessionInitialization(
5231
+ client,
5232
+ state,
5233
+ sessionId,
5234
+ logger,
5235
+ messages,
5236
+ config,
5237
+ projectDir
5238
+ );
5239
+ inflightInits.set(state, run);
5240
+ try {
5241
+ await run;
5242
+ } finally {
5243
+ inflightInits.delete(state);
5244
+ }
5245
+ }
5246
+ async function runSessionInitialization(client, state, sessionId, logger, messages, config, projectDir) {
5178
5247
  resetSessionState(state);
5179
5248
  state.sessionId = sessionId;
5180
5249
  state.storageDir = config?.storagePath ? resolveStorageDir(config.storagePath, projectDir ?? cwd()) : void 0;
@@ -5198,6 +5267,13 @@ async function ensureSessionInitialized(client, state, sessionId, logger, messag
5198
5267
  if (parentSessionId) {
5199
5268
  try {
5200
5269
  const parent = await loadSessionState(parentSessionId, logger);
5270
+ if (parent?.stickyTruncations) {
5271
+ for (const [callID, output] of Object.entries(parent.stickyTruncations)) {
5272
+ if (typeof output === "string") {
5273
+ state.stickyTruncations[callID] = output;
5274
+ }
5275
+ }
5276
+ }
5201
5277
  const response = parent ? await client.session.messages({ path: { id: parentSessionId } }) : void 0;
5202
5278
  const parentMessages = Array.isArray(response?.data) ? response.data : Array.isArray(response) ? response : [];
5203
5279
  if (parent && parentMessages.length > 0) {
@@ -5263,6 +5339,14 @@ async function ensureSessionInitialized(client, state, sessionId, logger, messag
5263
5339
  }
5264
5340
  }
5265
5341
  }
5342
+ const persistedSticky = persisted.stickyTruncations;
5343
+ if (persistedSticky && typeof persistedSticky === "object") {
5344
+ for (const [callID, output] of Object.entries(persistedSticky)) {
5345
+ if (typeof output === "string") {
5346
+ state.stickyTruncations[callID] = output;
5347
+ }
5348
+ }
5349
+ }
5266
5350
  const persistedAny = persisted;
5267
5351
  if (persistedAny._persistedMessageIds) {
5268
5352
  state.messageIds = {
@@ -8170,240 +8254,243 @@ function createCompressRangeTool(factoryCtx) {
8170
8254
  }
8171
8255
  }
8172
8256
  const callId = typeof toolCtx.callID === "string" ? toolCtx.callID : void 0;
8173
- const { rawMessages, searchContext } = await prepareSession(
8174
- ctx0,
8175
- toolCtx,
8176
- `Compress Range: ${input.topic ?? "(batch)"}`
8177
- );
8178
- const { providerId, modelId } = getModelInfo(rawMessages);
8179
- const ctx = {
8180
- ...ctx0,
8181
- config: applyCompressOverrides(ctx0.config, providerId, modelId)
8182
- };
8183
- const needsSmartPlan = requiresSmartPlan(
8184
- ctx.config.compress.smartPlanRequired === true,
8185
- input.content
8186
- );
8187
- if (needsSmartPlan && input.content.length !== 1) {
8188
- throw new Error(
8189
- 'Raw-message compression accepts exactly one canonical SMART PLAN range per call. Use the latest ACP nudge, or call acp_status({scope:"uncompressed"}) to refresh it.'
8257
+ const run = async () => {
8258
+ const { rawMessages, searchContext } = await prepareSession(
8259
+ ctx0,
8260
+ toolCtx,
8261
+ `Compress Range: ${input.topic ?? "(batch)"}`
8190
8262
  );
8191
- }
8192
- const { plans: filteredPlans, totalChars } = prepareExecutableRangePlans(
8193
- input,
8194
- searchContext,
8195
- ctx.state,
8196
- ctx.config,
8197
- ctx.logger
8198
- );
8199
- if (needsSmartPlan) {
8200
- validateSmartPlan(
8201
- toolCtx.sessionID,
8202
- filteredPlans[0].entry.startId,
8203
- filteredPlans[0].entry.endId,
8204
- filteredPlans[0].selection.messageIds,
8205
- totalChars,
8206
- ctx.state.prune.messages.structureVersion ?? 0
8207
- );
8208
- }
8209
- const notifications = [];
8210
- let preparedPlans = [];
8211
- let totalCompressedMessages = 0;
8212
- for (const plan of filteredPlans) {
8213
- const parsedPlaceholders = parseBlockPlaceholders(plan.entry.summary);
8214
- validateSummaryPlaceholders(
8215
- parsedPlaceholders,
8216
- plan.selection.requiredBlockIds,
8217
- plan.selection.startReference,
8218
- plan.selection.endReference,
8219
- searchContext.summaryByBlockId,
8220
- ctx.logger
8221
- );
8222
- const injected = injectBlockPlaceholders(
8223
- plan.entry.summary,
8224
- parsedPlaceholders,
8225
- searchContext.summaryByBlockId,
8226
- plan.selection.startReference,
8227
- plan.selection.endReference
8228
- );
8229
- const summaryWithUsers = appendProtectedUserMessages(
8230
- injected.expandedSummary,
8231
- plan.selection,
8232
- searchContext,
8233
- ctx.state,
8234
- ctx.config.compress.protectUserMessages
8263
+ const { providerId, modelId } = getModelInfo(rawMessages);
8264
+ const ctx = {
8265
+ ...ctx0,
8266
+ config: applyCompressOverrides(ctx0.config, providerId, modelId)
8267
+ };
8268
+ const needsSmartPlan = requiresSmartPlan(
8269
+ ctx.config.compress.smartPlanRequired === true,
8270
+ input.content
8235
8271
  );
8236
- const summaryWithPromptInfo = appendProtectedPromptInfo(
8237
- summaryWithUsers,
8238
- plan.selection,
8272
+ if (needsSmartPlan && input.content.length !== 1) {
8273
+ throw new Error(
8274
+ 'Raw-message compression accepts exactly one canonical SMART PLAN range per call. Use the latest ACP nudge, or call acp_status({scope:"uncompressed"}) to refresh it.'
8275
+ );
8276
+ }
8277
+ const { plans: filteredPlans, totalChars } = prepareExecutableRangePlans(
8278
+ input,
8239
8279
  searchContext,
8240
8280
  ctx.state,
8241
- ctx.config.compress.protectTags
8242
- );
8243
- const summaryWithTools = await appendProtectedTools(
8244
- ctx.client,
8245
- ctx.state,
8246
- summaryWithPromptInfo,
8247
- plan.selection,
8248
- searchContext,
8249
- ctx.config.compress.protectedTools,
8250
- ctx.config.protectedFilePatterns
8251
- );
8252
- const completedSummary = appendMissingBlockSummaries(
8253
- summaryWithTools,
8254
- [],
8255
- searchContext.summaryByBlockId,
8256
- injected.consumedBlockIds
8257
- );
8258
- const boundaryConsumed = extractBoundaryConsumedBlocks2(
8259
- plan.selection.startReference,
8260
- plan.selection.endReference
8281
+ ctx.config,
8282
+ ctx.logger
8261
8283
  );
8262
- const seenConsumed = /* @__PURE__ */ new Set();
8263
- const mergeConsumedBlockIds = [
8264
- ...plan.selection.requiredBlockIds,
8265
- ...boundaryConsumed
8266
- ].filter((id) => {
8267
- if (seenConsumed.has(id)) return false;
8268
- seenConsumed.add(id);
8269
- return true;
8270
- });
8271
- preparedPlans.push({
8272
- entry: plan.entry,
8273
- selection: plan.selection,
8274
- anchorMessageId: plan.anchorMessageId,
8275
- finalSummary: appendArchivedImagePointers(
8276
- completedSummary.expandedSummary,
8284
+ if (needsSmartPlan) {
8285
+ validateSmartPlan(
8286
+ toolCtx.sessionID,
8287
+ filteredPlans[0].entry.startId,
8288
+ filteredPlans[0].entry.endId,
8289
+ filteredPlans[0].selection.messageIds,
8290
+ totalChars,
8291
+ ctx.state.prune.messages.structureVersion ?? 0
8292
+ );
8293
+ }
8294
+ const notifications = [];
8295
+ let preparedPlans = [];
8296
+ let totalCompressedMessages = 0;
8297
+ for (const plan of filteredPlans) {
8298
+ const parsedPlaceholders = parseBlockPlaceholders(plan.entry.summary);
8299
+ validateSummaryPlaceholders(
8300
+ parsedPlaceholders,
8301
+ plan.selection.requiredBlockIds,
8302
+ plan.selection.startReference,
8303
+ plan.selection.endReference,
8304
+ searchContext.summaryByBlockId,
8305
+ ctx.logger
8306
+ );
8307
+ const injected = injectBlockPlaceholders(
8308
+ plan.entry.summary,
8309
+ parsedPlaceholders,
8310
+ searchContext.summaryByBlockId,
8311
+ plan.selection.startReference,
8312
+ plan.selection.endReference
8313
+ );
8314
+ const summaryWithUsers = appendProtectedUserMessages(
8315
+ injected.expandedSummary,
8277
8316
  plan.selection,
8317
+ searchContext,
8318
+ ctx.state,
8319
+ ctx.config.compress.protectUserMessages
8320
+ );
8321
+ const summaryWithPromptInfo = appendProtectedPromptInfo(
8322
+ summaryWithUsers,
8323
+ plan.selection,
8324
+ searchContext,
8325
+ ctx.state,
8326
+ ctx.config.compress.protectTags
8327
+ );
8328
+ const summaryWithTools = await appendProtectedTools(
8329
+ ctx.client,
8330
+ ctx.state,
8331
+ summaryWithPromptInfo,
8332
+ plan.selection,
8333
+ searchContext,
8334
+ ctx.config.compress.protectedTools,
8335
+ ctx.config.protectedFilePatterns
8336
+ );
8337
+ const completedSummary = appendMissingBlockSummaries(
8338
+ summaryWithTools,
8339
+ [],
8340
+ searchContext.summaryByBlockId,
8341
+ injected.consumedBlockIds
8342
+ );
8343
+ const boundaryConsumed = extractBoundaryConsumedBlocks2(
8344
+ plan.selection.startReference,
8345
+ plan.selection.endReference
8346
+ );
8347
+ const seenConsumed = /* @__PURE__ */ new Set();
8348
+ const mergeConsumedBlockIds = [
8349
+ ...plan.selection.requiredBlockIds,
8350
+ ...boundaryConsumed
8351
+ ].filter((id) => {
8352
+ if (seenConsumed.has(id)) return false;
8353
+ seenConsumed.add(id);
8354
+ return true;
8355
+ });
8356
+ preparedPlans.push({
8357
+ entry: plan.entry,
8358
+ selection: plan.selection,
8359
+ anchorMessageId: plan.anchorMessageId,
8360
+ finalSummary: appendArchivedImagePointers(
8361
+ completedSummary.expandedSummary,
8362
+ plan.selection,
8363
+ ctx.state,
8364
+ ctx.config.compress.images?.enabled !== false
8365
+ ),
8366
+ consumedBlockIds: mergeConsumedBlockIds
8367
+ });
8368
+ }
8369
+ const partition = partitionPhantomPlans(
8370
+ identifyPhantomPlans(
8278
8371
  ctx.state,
8279
- ctx.config.compress.images?.enabled !== false
8372
+ preparedPlans.map((p) => ({
8373
+ messageIds: p.selection.messageIds,
8374
+ consumedBlockIds: p.consumedBlockIds
8375
+ }))
8280
8376
  ),
8281
- consumedBlockIds: mergeConsumedBlockIds
8282
- });
8283
- }
8284
- const partition = partitionPhantomPlans(
8285
- identifyPhantomPlans(
8286
- ctx.state,
8287
- preparedPlans.map((p) => ({
8288
- messageIds: p.selection.messageIds,
8289
- consumedBlockIds: p.consumedBlockIds
8290
- }))
8291
- ),
8292
- preparedPlans.length
8293
- );
8294
- let phantomSkipNotice = null;
8295
- if (partition.kind === "all-phantom") {
8296
- ctx.logger.warn("Batch compress: ALL entries phantom", {
8297
- totalCount: preparedPlans.length,
8298
- details: partition.details
8299
- });
8300
- throw new Error(buildPhantomErrorMessage(partition.details));
8301
- }
8302
- if (partition.kind === "partial") {
8303
- ctx.logger.warn("Batch compress: phantom entries detected", {
8304
- phantomCount: partition.dropIndices.length,
8305
- totalCount: preparedPlans.length,
8306
- phantomIndices: partition.dropIndices,
8307
- details: partition.details
8308
- });
8309
- const dropSet = new Set(partition.dropIndices);
8310
- preparedPlans = preparedPlans.filter((_, i) => !dropSet.has(i));
8311
- phantomSkipNotice = partition.notice;
8312
- }
8313
- const acknowledgeRisk = args.acknowledgeRisk === true;
8314
- const qualityGateRetryPendingBefore = ctx.state.qualityGateRetryPending;
8315
- const bypassQuality = acknowledgeRisk && ctx.state.qualityGateRetryPending;
8316
- const ignoredAcknowledgeRisk = acknowledgeRisk && !ctx.state.qualityGateRetryPending;
8317
- if (ignoredAcknowledgeRisk) {
8318
- ctx.logger.warn(
8319
- "compress: acknowledgeRisk ignored \u2014 no quality gate rejection pending"
8377
+ preparedPlans.length
8320
8378
  );
8321
- }
8322
- ctx.state.qualityGateRetryPending = false;
8323
- if (!bypassQuality) {
8324
- for (const plan of preparedPlans) {
8325
- const result = evaluatePreCommitQuality(
8326
- rawMessages,
8327
- plan.selection.messageIds,
8328
- plan.selection.messageTokenById,
8329
- plan.finalSummary,
8330
- ctx.config,
8331
- ctx.logger
8379
+ let phantomSkipNotice = null;
8380
+ if (partition.kind === "all-phantom") {
8381
+ ctx.logger.warn("Batch compress: ALL entries phantom", {
8382
+ totalCount: preparedPlans.length,
8383
+ details: partition.details
8384
+ });
8385
+ throw new Error(buildPhantomErrorMessage(partition.details));
8386
+ }
8387
+ if (partition.kind === "partial") {
8388
+ ctx.logger.warn("Batch compress: phantom entries detected", {
8389
+ phantomCount: partition.dropIndices.length,
8390
+ totalCount: preparedPlans.length,
8391
+ phantomIndices: partition.dropIndices,
8392
+ details: partition.details
8393
+ });
8394
+ const dropSet = new Set(partition.dropIndices);
8395
+ preparedPlans = preparedPlans.filter((_, i) => !dropSet.has(i));
8396
+ phantomSkipNotice = partition.notice;
8397
+ }
8398
+ const acknowledgeRisk = args.acknowledgeRisk === true;
8399
+ const qualityGateRetryPendingBefore = ctx.state.qualityGateRetryPending;
8400
+ const bypassQuality = acknowledgeRisk && ctx.state.qualityGateRetryPending;
8401
+ const ignoredAcknowledgeRisk = acknowledgeRisk && !ctx.state.qualityGateRetryPending;
8402
+ if (ignoredAcknowledgeRisk) {
8403
+ ctx.logger.warn(
8404
+ "compress: acknowledgeRisk ignored \u2014 no quality gate rejection pending"
8332
8405
  );
8333
- if (result && !result.passed) {
8334
- ctx.state.qualityGateRetryPending = true;
8335
- throw buildQualityRejectionError(
8336
- {
8337
- startId: plan.entry.startId,
8338
- endId: plan.entry.endId,
8339
- summary: plan.finalSummary,
8340
- messageIds: plan.selection.messageIds,
8341
- messageTokenById: plan.selection.messageTokenById
8342
- },
8343
- result,
8406
+ }
8407
+ ctx.state.qualityGateRetryPending = false;
8408
+ if (!bypassQuality) {
8409
+ for (const plan of preparedPlans) {
8410
+ const result = evaluatePreCommitQuality(
8411
+ rawMessages,
8412
+ plan.selection.messageIds,
8413
+ plan.selection.messageTokenById,
8414
+ plan.finalSummary,
8415
+ ctx.config,
8344
8416
  ctx.logger
8345
8417
  );
8418
+ if (result && !result.passed) {
8419
+ ctx.state.qualityGateRetryPending = true;
8420
+ throw buildQualityRejectionError(
8421
+ {
8422
+ startId: plan.entry.startId,
8423
+ endId: plan.entry.endId,
8424
+ summary: plan.finalSummary,
8425
+ messageIds: plan.selection.messageIds,
8426
+ messageTokenById: plan.selection.messageTokenById
8427
+ },
8428
+ result,
8429
+ ctx.logger
8430
+ );
8431
+ }
8346
8432
  }
8347
8433
  }
8348
- }
8349
- const snapshot = snapshotCompressionState(ctx.state);
8350
- const runId = allocateRunId(ctx.state);
8351
- try {
8352
- for (const preparedPlan of preparedPlans) {
8353
- const blockId = allocateBlockId(ctx.state);
8354
- const keepResult = resolveKeepMarkers(
8355
- preparedPlan.finalSummary,
8356
- rawMessages,
8357
- ctx.state,
8358
- ctx.config
8359
- );
8360
- preparedPlan.finalSummary = keepResult.summary;
8361
- const storedSummary = wrapCompressedSummary(blockId, preparedPlan.finalSummary);
8362
- const summaryTokens = countTokens2(storedSummary);
8363
- const applied = applyCompressionState(
8364
- ctx.state,
8365
- {
8366
- topic: preparedPlan.entry.topic ?? input.topic ?? "",
8367
- batchTopic: input.topic,
8368
- startId: preparedPlan.entry.startId,
8369
- endId: preparedPlan.entry.endId,
8370
- mode: "range",
8434
+ const snapshot = snapshotCompressionState(ctx.state);
8435
+ const runId = allocateRunId(ctx.state);
8436
+ try {
8437
+ for (const preparedPlan of preparedPlans) {
8438
+ const blockId = allocateBlockId(ctx.state);
8439
+ const keepResult = resolveKeepMarkers(
8440
+ preparedPlan.finalSummary,
8441
+ rawMessages,
8442
+ ctx.state,
8443
+ ctx.config
8444
+ );
8445
+ preparedPlan.finalSummary = keepResult.summary;
8446
+ const storedSummary = wrapCompressedSummary(blockId, preparedPlan.finalSummary);
8447
+ const summaryTokens = countTokens2(storedSummary);
8448
+ const applied = applyCompressionState(
8449
+ ctx.state,
8450
+ {
8451
+ topic: preparedPlan.entry.topic ?? input.topic ?? "",
8452
+ batchTopic: input.topic,
8453
+ startId: preparedPlan.entry.startId,
8454
+ endId: preparedPlan.entry.endId,
8455
+ mode: "range",
8456
+ runId,
8457
+ compressMessageId: toolCtx.messageID,
8458
+ compressCallId: callId,
8459
+ summaryTokens
8460
+ },
8461
+ preparedPlan.selection,
8462
+ preparedPlan.anchorMessageId,
8463
+ blockId,
8464
+ storedSummary,
8465
+ preparedPlan.consumedBlockIds,
8466
+ ctx.config.gc
8467
+ );
8468
+ totalCompressedMessages += applied.messageIds.length;
8469
+ notifications.push({
8470
+ blockId,
8371
8471
  runId,
8372
- compressMessageId: toolCtx.messageID,
8373
- compressCallId: callId,
8472
+ summary: preparedPlan.finalSummary,
8374
8473
  summaryTokens
8375
- },
8376
- preparedPlan.selection,
8377
- preparedPlan.anchorMessageId,
8378
- blockId,
8379
- storedSummary,
8380
- preparedPlan.consumedBlockIds,
8381
- ctx.config.gc
8382
- );
8383
- totalCompressedMessages += applied.messageIds.length;
8384
- notifications.push({
8385
- blockId,
8386
- runId,
8387
- summary: preparedPlan.finalSummary,
8388
- summaryTokens
8389
- });
8474
+ });
8475
+ }
8476
+ await finalizeSession(ctx, toolCtx, rawMessages, notifications, input.topic);
8477
+ if (needsSmartPlan) consumeSmartPlan(toolCtx.sessionID);
8478
+ } catch (error) {
8479
+ restoreCompressionState(ctx.state, snapshot);
8480
+ ctx.state.qualityGateRetryPending = qualityGateRetryPendingBefore;
8481
+ throw error;
8390
8482
  }
8391
- await finalizeSession(ctx, toolCtx, rawMessages, notifications, input.topic);
8392
- if (needsSmartPlan) consumeSmartPlan(toolCtx.sessionID);
8393
- } catch (error) {
8394
- restoreCompressionState(ctx.state, snapshot);
8395
- ctx.state.qualityGateRetryPending = qualityGateRetryPendingBefore;
8396
- throw error;
8397
- }
8398
- const skippedNote = phantomSkipNotice !== null ? `
8483
+ const skippedNote = phantomSkipNotice !== null ? `
8399
8484
  \u26A0\uFE0F ${phantomSkipNotice}
8400
8485
  ` : "";
8401
- const ackNote = ignoredAcknowledgeRisk ? `
8486
+ const ackNote = ignoredAcknowledgeRisk ? `
8402
8487
  \u26A0\uFE0F acknowledgeRisk was ignored: no quality gate rejection was pending, so quality checks ran normally. Only pass it when retrying immediately after a quality gate rejection.
8403
8488
  ` : "";
8404
- return `Compressed ${totalCompressedMessages} messages into ${COMPRESSED_BLOCK_HEADER}.${skippedNote}${ackNote}
8489
+ return `Compressed ${totalCompressedMessages} messages into ${COMPRESSED_BLOCK_HEADER}.${skippedNote}${ackNote}
8405
8490
  IMPORTANT: This was an automatic context compression. You MUST continue your previous task exactly where you left off. Do NOT ask the user what to do next.
8406
8491
  \u{1F4A1} Tip: Use search_context('keyword') to find compressed content when you need it later.`;
8492
+ };
8493
+ return factoryCtx.registry.withSessionGuard(toolCtx.sessionID, () => run());
8407
8494
  }
8408
8495
  });
8409
8496
  }
@@ -10439,139 +10526,142 @@ function createDecompressTool(factoryCtx) {
10439
10526
  args: buildSchema2(),
10440
10527
  async execute(args, toolCtx) {
10441
10528
  const ctx = resolveToolContext(factoryCtx, toolCtx.sessionID);
10442
- const { rawMessages } = await prepareDecompressSession(ctx, toolCtx);
10443
- const effectiveLimitBefore = resolveEffectiveContextLimit(ctx.state, ctx.config);
10444
- const contextUsageBefore = effectiveLimitBefore ? Math.round(
10445
- getCurrentTokenUsage(ctx.state, rawMessages) / effectiveLimitBefore.limit * 100
10446
- ) : void 0;
10447
- const resolved = resolveTargets(args, ctx.state, rawMessages, ctx.logger);
10448
- if (!resolved.ok) {
10449
- return resolved.error;
10450
- }
10451
- const targets = resolved.targets;
10452
- const messagesState = ctx.state.prune.messages;
10453
- const activeBlocks = [];
10454
- for (const target of targets) {
10455
- for (const block of target.blocks) {
10456
- if (block.active) {
10457
- activeBlocks.push(block);
10458
- }
10529
+ const run = async () => {
10530
+ const { rawMessages } = await prepareDecompressSession(ctx, toolCtx);
10531
+ const effectiveLimitBefore = resolveEffectiveContextLimit(ctx.state, ctx.config);
10532
+ const contextUsageBefore = effectiveLimitBefore ? Math.round(
10533
+ getCurrentTokenUsage(ctx.state, rawMessages) / effectiveLimitBefore.limit * 100
10534
+ ) : void 0;
10535
+ const resolved = resolveTargets(args, ctx.state, rawMessages, ctx.logger);
10536
+ if (!resolved.ok) {
10537
+ return resolved.error;
10459
10538
  }
10460
- }
10461
- if (args.toFile) {
10462
- const targetPath = args.toFile;
10463
- const os = await import("os");
10464
- const path = await import("path");
10465
- const allowedDirs = [
10466
- os.tmpdir() + "/",
10467
- path.join(os.homedir(), ".cache", "opencode") + "/"
10468
- ];
10469
- const resolvedPath = path.resolve(targetPath);
10470
- const isAllowed = allowedDirs.some((dir) => {
10471
- const rel = path.relative(dir, resolvedPath);
10472
- return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
10473
- });
10474
- if (!isAllowed) {
10475
- return `Error: toFile path must be under ${os.tmpdir()} or ~/.cache/opencode/. Got: ${targetPath}`;
10539
+ const targets = resolved.targets;
10540
+ const messagesState = ctx.state.prune.messages;
10541
+ const activeBlocks = [];
10542
+ for (const target of targets) {
10543
+ for (const block of target.blocks) {
10544
+ if (block.active) {
10545
+ activeBlocks.push(block);
10546
+ }
10547
+ }
10476
10548
  }
10477
- const msgIdSet = /* @__PURE__ */ new Set();
10478
- for (const block of activeBlocks) {
10479
- for (const id of block.effectiveMessageIds ?? []) {
10480
- msgIdSet.add(id);
10549
+ if (args.toFile) {
10550
+ const targetPath = args.toFile;
10551
+ const os = await import("os");
10552
+ const path = await import("path");
10553
+ const allowedDirs = [
10554
+ os.tmpdir() + "/",
10555
+ path.join(os.homedir(), ".cache", "opencode") + "/"
10556
+ ];
10557
+ const resolvedPath = path.resolve(targetPath);
10558
+ const isAllowed = allowedDirs.some((dir) => {
10559
+ const rel = path.relative(dir, resolvedPath);
10560
+ return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
10561
+ });
10562
+ if (!isAllowed) {
10563
+ return `Error: toFile path must be under ${os.tmpdir()} or ~/.cache/opencode/. Got: ${targetPath}`;
10481
10564
  }
10565
+ const msgIdSet = /* @__PURE__ */ new Set();
10566
+ for (const block of activeBlocks) {
10567
+ for (const id of block.effectiveMessageIds ?? []) {
10568
+ msgIdSet.add(id);
10569
+ }
10570
+ }
10571
+ const blockMessages = rawMessages.filter((m) => msgIdSet.has(extractMessageId(m)));
10572
+ const lines2 = blockMessages.map(extractMessageText2);
10573
+ const { writeFile: writeFile4 } = await import("fs/promises");
10574
+ let fileContent;
10575
+ let sourceNote;
10576
+ if (lines2.length > 0) {
10577
+ fileContent = lines2.join("\n\n---\n\n");
10578
+ sourceNote = `${blockMessages.length} original message${blockMessages.length === 1 ? "" : "s"}`;
10579
+ } else {
10580
+ fileContent = targets[0]?.blocks[0]?.summary ?? "(no content available)";
10581
+ sourceNote = `no original messages found; wrote block summary (${targets.length} block${targets.length === 1 ? "" : "s"})`;
10582
+ }
10583
+ await writeFile4(targetPath, fileContent, "utf-8");
10584
+ const displayIds2 = targets.map((t) => `b${t.displayId}`).join(", ");
10585
+ return `Block(s) ${displayIds2} content (${sourceNote}, ${fileContent.length} chars) written to ${targetPath}. Block(s) stay compressed \u2014 context unchanged. Use read tool to access specific parts.`;
10482
10586
  }
10483
- const blockMessages = rawMessages.filter((m) => msgIdSet.has(extractMessageId(m)));
10484
- const lines2 = blockMessages.map(extractMessageText2);
10485
- const { writeFile: writeFile4 } = await import("fs/promises");
10486
- let fileContent;
10487
- let sourceNote;
10488
- if (lines2.length > 0) {
10489
- fileContent = lines2.join("\n\n---\n\n");
10490
- sourceNote = `${blockMessages.length} original message${blockMessages.length === 1 ? "" : "s"}`;
10491
- } else {
10492
- fileContent = targets[0]?.blocks[0]?.summary ?? "(no content available)";
10493
- sourceNote = `no original messages found; wrote block summary (${targets.length} block${targets.length === 1 ? "" : "s"})`;
10494
- }
10495
- await writeFile4(targetPath, fileContent, "utf-8");
10496
- const displayIds2 = targets.map((t) => `b${t.displayId}`).join(", ");
10497
- return `Block(s) ${displayIds2} content (${sourceNote}, ${fileContent.length} chars) written to ${targetPath}. Block(s) stay compressed \u2014 context unchanged. Use read tool to access specific parts.`;
10498
- }
10499
- const availability = checkDecompressSourceAvailability(
10500
- messagesState,
10501
- targets,
10502
- { full: args.full === true },
10503
- new Set(rawMessages.map((m) => m.info.id))
10504
- );
10505
- if (availability.missingMessageIds.length > 0) {
10506
- const displayIds2 = targets.map((t) => `b${t.displayId}`).join(", ");
10507
- const missingRefs = availability.missingMessageIds.map(
10508
- (id) => ctx.state.messageIds.byRawId.get(id) ?? id
10587
+ const availability = checkDecompressSourceAvailability(
10588
+ messagesState,
10589
+ targets,
10590
+ { full: args.full === true },
10591
+ new Set(rawMessages.map((m) => m.info.id))
10509
10592
  );
10510
- const shownRefs = missingRefs.slice(0, 10).join(", ");
10511
- const extraCount = missingRefs.length - Math.min(missingRefs.length, 10);
10512
- ctx.logger.warn("Decompress aborted: source messages missing from host history", {
10513
- targetDisplayIds: displayIds2,
10514
- full: args.full === true,
10515
- requiredCount: availability.requiredMessageIds.length,
10516
- missingCount: availability.missingMessageIds.length,
10517
- missingRefs
10593
+ if (availability.missingMessageIds.length > 0) {
10594
+ const displayIds2 = targets.map((t) => `b${t.displayId}`).join(", ");
10595
+ const missingRefs = availability.missingMessageIds.map(
10596
+ (id) => ctx.state.messageIds.byRawId.get(id) ?? id
10597
+ );
10598
+ const shownRefs = missingRefs.slice(0, 10).join(", ");
10599
+ const extraCount = missingRefs.length - Math.min(missingRefs.length, 10);
10600
+ ctx.logger.warn("Decompress aborted: source messages missing from host history", {
10601
+ targetDisplayIds: displayIds2,
10602
+ full: args.full === true,
10603
+ requiredCount: availability.requiredMessageIds.length,
10604
+ missingCount: availability.missingMessageIds.length,
10605
+ missingRefs
10606
+ });
10607
+ return `Error: Cannot decompress ${displayIds2}: ${availability.missingMessageIds.length} of ${availability.requiredMessageIds.length} source message(s) are no longer present in session history (removed by native compaction or external deletion). Missing: ${shownRefs}` + (extraCount > 0 ? ` (+${extraCount} more)` : "") + `. Block(s) stay compressed \u2014 the summary remains available and nothing was changed. This is a missing-source condition, not a transient fetch failure.`;
10608
+ }
10609
+ const activeMessagesBefore = snapshotActiveMessages(messagesState);
10610
+ const activeBlockIdsBefore = new Set(messagesState.activeBlockIds);
10611
+ for (const target of targets) {
10612
+ deactivateCompressionTarget(messagesState, target, { full: args.full === true });
10613
+ }
10614
+ syncCompressionBlocks(ctx.state, ctx.logger, rawMessages);
10615
+ const { restoredMessageCount, restoredTokens } = computeRestoredMessages(
10616
+ messagesState,
10617
+ activeMessagesBefore
10618
+ );
10619
+ const reactivatedBlockIds = computeReactivatedBlockIds(
10620
+ messagesState,
10621
+ activeBlockIdsBefore
10622
+ );
10623
+ ctx.state.stats.totalPruneTokens = Math.max(
10624
+ 0,
10625
+ ctx.state.stats.totalPruneTokens - restoredTokens
10626
+ );
10627
+ const effectiveLimitAfter = resolveEffectiveContextLimit(ctx.state, ctx.config);
10628
+ const contextUsageAfter = effectiveLimitAfter ? Math.round(
10629
+ getCurrentTokenUsage(ctx.state, rawMessages) / effectiveLimitAfter.limit * 100
10630
+ ) : void 0;
10631
+ await finalizeDecompressSession(ctx);
10632
+ const restoredContentPreview = buildRestoredContentPreview(
10633
+ rawMessages,
10634
+ activeMessagesBefore,
10635
+ messagesState
10636
+ );
10637
+ const displayIds = targets.map((t) => `b${t.displayId}`).join(", ");
10638
+ const lines = [];
10639
+ const headerNoun = targets.length === 1 ? "block" : "blocks";
10640
+ lines.push(
10641
+ `Decompressed ${headerNoun} ${displayIds}. Restored ${restoredMessageCount} message(s) (~${formatTokenCount(restoredTokens)}).`
10642
+ );
10643
+ if (contextUsageBefore !== void 0 && contextUsageAfter !== void 0) {
10644
+ lines.push(`Context usage: ${contextUsageBefore}% \u2192 ${contextUsageAfter}%.`);
10645
+ }
10646
+ if (reactivatedBlockIds.length > 0) {
10647
+ const refs = reactivatedBlockIds.map((id) => `b${id}`).join(", ");
10648
+ lines.push(`Also restored nested block(s): ${refs}.`);
10649
+ }
10650
+ if (restoredContentPreview) {
10651
+ lines.push("");
10652
+ lines.push("RESTORED CONTENT (condensed):");
10653
+ lines.push(restoredContentPreview);
10654
+ }
10655
+ ctx.logger.info("Decompress tool completed", {
10656
+ mode: typeof args.startId === "string" ? "range" : "block",
10657
+ targetBlockIds: targets.map((t) => t.displayId),
10658
+ restoredMessageCount,
10659
+ restoredTokens,
10660
+ reactivatedBlockIds
10518
10661
  });
10519
- return `Error: Cannot decompress ${displayIds2}: ${availability.missingMessageIds.length} of ${availability.requiredMessageIds.length} source message(s) are no longer present in session history (removed by native compaction or external deletion). Missing: ${shownRefs}` + (extraCount > 0 ? ` (+${extraCount} more)` : "") + `. Block(s) stay compressed \u2014 the summary remains available and nothing was changed. This is a missing-source condition, not a transient fetch failure.`;
10520
- }
10521
- const activeMessagesBefore = snapshotActiveMessages(messagesState);
10522
- const activeBlockIdsBefore = new Set(messagesState.activeBlockIds);
10523
- for (const target of targets) {
10524
- deactivateCompressionTarget(messagesState, target, { full: args.full === true });
10525
- }
10526
- syncCompressionBlocks(ctx.state, ctx.logger, rawMessages);
10527
- const { restoredMessageCount, restoredTokens } = computeRestoredMessages(
10528
- messagesState,
10529
- activeMessagesBefore
10530
- );
10531
- const reactivatedBlockIds = computeReactivatedBlockIds(
10532
- messagesState,
10533
- activeBlockIdsBefore
10534
- );
10535
- ctx.state.stats.totalPruneTokens = Math.max(
10536
- 0,
10537
- ctx.state.stats.totalPruneTokens - restoredTokens
10538
- );
10539
- const effectiveLimitAfter = resolveEffectiveContextLimit(ctx.state, ctx.config);
10540
- const contextUsageAfter = effectiveLimitAfter ? Math.round(
10541
- getCurrentTokenUsage(ctx.state, rawMessages) / effectiveLimitAfter.limit * 100
10542
- ) : void 0;
10543
- await finalizeDecompressSession(ctx);
10544
- const restoredContentPreview = buildRestoredContentPreview(
10545
- rawMessages,
10546
- activeMessagesBefore,
10547
- messagesState
10548
- );
10549
- const displayIds = targets.map((t) => `b${t.displayId}`).join(", ");
10550
- const lines = [];
10551
- const headerNoun = targets.length === 1 ? "block" : "blocks";
10552
- lines.push(
10553
- `Decompressed ${headerNoun} ${displayIds}. Restored ${restoredMessageCount} message(s) (~${formatTokenCount(restoredTokens)}).`
10554
- );
10555
- if (contextUsageBefore !== void 0 && contextUsageAfter !== void 0) {
10556
- lines.push(`Context usage: ${contextUsageBefore}% \u2192 ${contextUsageAfter}%.`);
10557
- }
10558
- if (reactivatedBlockIds.length > 0) {
10559
- const refs = reactivatedBlockIds.map((id) => `b${id}`).join(", ");
10560
- lines.push(`Also restored nested block(s): ${refs}.`);
10561
- }
10562
- if (restoredContentPreview) {
10563
- lines.push("");
10564
- lines.push("RESTORED CONTENT (condensed):");
10565
- lines.push(restoredContentPreview);
10566
- }
10567
- ctx.logger.info("Decompress tool completed", {
10568
- mode: typeof args.startId === "string" ? "range" : "block",
10569
- targetBlockIds: targets.map((t) => t.displayId),
10570
- restoredMessageCount,
10571
- restoredTokens,
10572
- reactivatedBlockIds
10573
- });
10574
- return lines.join("\n");
10662
+ return lines.join("\n");
10663
+ };
10664
+ return factoryCtx.registry.withSessionGuard(toolCtx.sessionID, () => run());
10575
10665
  }
10576
10666
  });
10577
10667
  }
@@ -11329,7 +11419,7 @@ import { writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
11329
11419
  import { join as join5 } from "path";
11330
11420
  import { existsSync as existsSync5 } from "fs";
11331
11421
  import { homedir as homedir3 } from "os";
11332
- var LOG_VERSION = true ? "1.18.4" : "dev";
11422
+ var LOG_VERSION = true ? "1.18.5-pr.408.227" : "dev";
11333
11423
  var LEVEL_RANK = {
11334
11424
  debug: 10,
11335
11425
  info: 20,
@@ -12184,6 +12274,7 @@ function truncateLargeToolOutputs(state, config, logger, messages) {
12184
12274
  const part = parts[pi];
12185
12275
  if (part?.type !== "tool") continue;
12186
12276
  if (part.state?.status !== "completed") continue;
12277
+ if (part.tool === "compress") continue;
12187
12278
  const content = extractCompletedToolOutput(part);
12188
12279
  if (content === void 0) continue;
12189
12280
  if (content === "[Old tool result content cleared]") continue;
@@ -12224,6 +12315,74 @@ function truncateLargeToolOutputs(state, config, logger, messages) {
12224
12315
  }
12225
12316
  }
12226
12317
 
12318
+ // lib/messages/sticky-truncation.ts
12319
+ function collectToolParts(messages) {
12320
+ const parts = [];
12321
+ for (const message of messages) {
12322
+ const messageParts = Array.isArray(message.parts) ? message.parts : [];
12323
+ for (const part of messageParts) {
12324
+ if (part?.type === "tool") {
12325
+ parts.push(part);
12326
+ }
12327
+ }
12328
+ }
12329
+ return parts;
12330
+ }
12331
+ function applyStickyTruncations(state, messages, logger) {
12332
+ const frozen = state.stickyTruncations;
12333
+ if (Object.keys(frozen).length === 0) return;
12334
+ let replayed = 0;
12335
+ const seen = /* @__PURE__ */ new Set();
12336
+ for (const part of collectToolParts(messages)) {
12337
+ const callID = typeof part.callID === "string" ? part.callID : void 0;
12338
+ if (!callID) continue;
12339
+ seen.add(callID);
12340
+ const recorded = frozen[callID];
12341
+ if (recorded === void 0) continue;
12342
+ if (!part.state) continue;
12343
+ if (part.state.output === recorded) continue;
12344
+ part.state.output = recorded;
12345
+ replayed++;
12346
+ }
12347
+ for (const callID of Object.keys(frozen)) {
12348
+ if (!seen.has(callID)) delete frozen[callID];
12349
+ }
12350
+ if (replayed > 0) {
12351
+ logger.debug("Sticky truncation: replayed frozen tool outputs", {
12352
+ replayed,
12353
+ frozen: Object.keys(frozen).length
12354
+ });
12355
+ }
12356
+ }
12357
+ function snapshotToolOutputs(messages) {
12358
+ const snapshot = /* @__PURE__ */ new Map();
12359
+ for (const part of collectToolParts(messages)) {
12360
+ const callID = typeof part.callID === "string" ? part.callID : void 0;
12361
+ if (!callID) continue;
12362
+ const content = extractCompletedToolOutput(part);
12363
+ if (content === void 0) continue;
12364
+ snapshot.set(callID, content);
12365
+ }
12366
+ return snapshot;
12367
+ }
12368
+ function recordStickyTruncations(state, messages, before, logger) {
12369
+ let recorded = 0;
12370
+ for (const part of collectToolParts(messages)) {
12371
+ const callID = typeof part.callID === "string" ? part.callID : void 0;
12372
+ if (!callID) continue;
12373
+ if (typeof part.state?.output !== "string") continue;
12374
+ const prior = before.get(callID);
12375
+ if (prior === void 0 || prior === part.state.output) continue;
12376
+ if (state.stickyTruncations[callID] === part.state.output) continue;
12377
+ state.stickyTruncations[callID] = part.state.output;
12378
+ recorded++;
12379
+ }
12380
+ if (recorded > 0) {
12381
+ logger.info("Sticky truncation: froze truncated tool outputs", { recorded });
12382
+ }
12383
+ return recorded;
12384
+ }
12385
+
12227
12386
  // lib/messages/enforce-budget.ts
12228
12387
  var DEFAULT_COMPLETION_RESERVE_TOKENS = 32768;
12229
12388
  var TRUNCATION_MARKER2 = "[truncated for context space";
@@ -13393,22 +13552,24 @@ function createSystemPromptHandler(registry4, logger, config, prompts) {
13393
13552
  logger.info("Skipping DCP system prompt injection for internal agent");
13394
13553
  return;
13395
13554
  }
13396
- if (input.model?.limit?.context) {
13397
- const limit = input.model.limit.context;
13398
- const providerID = input.model?.providerID;
13399
- const modelID = input.model?.id;
13400
- const changed = state.modelContextLimit !== limit || providerID !== void 0 && state.modelProviderID !== providerID || modelID !== void 0 && state.modelID !== modelID;
13401
- state.modelContextLimit = limit;
13402
- if (providerID !== void 0) {
13403
- state.modelProviderID = providerID;
13404
- }
13405
- if (modelID !== void 0) {
13406
- state.modelID = modelID;
13407
- }
13408
- if (changed) {
13409
- saveSessionState(state, logger).catch(() => {
13410
- });
13411
- }
13555
+ if (input.model?.limit?.context && input.sessionID) {
13556
+ await registry4.withSessionGuard(input.sessionID, () => {
13557
+ const limit = input.model.limit.context;
13558
+ const providerID = input.model?.providerID;
13559
+ const modelID = input.model?.id;
13560
+ const changed = state.modelContextLimit !== limit || providerID !== void 0 && state.modelProviderID !== providerID || modelID !== void 0 && state.modelID !== modelID;
13561
+ state.modelContextLimit = limit;
13562
+ if (providerID !== void 0) {
13563
+ state.modelProviderID = providerID;
13564
+ }
13565
+ if (modelID !== void 0) {
13566
+ state.modelID = modelID;
13567
+ }
13568
+ if (changed) {
13569
+ saveSessionState(state, logger).catch(() => {
13570
+ });
13571
+ }
13572
+ });
13412
13573
  }
13413
13574
  const effectivePermission = compressPermission(state, config);
13414
13575
  if (effectivePermission === "deny") {
@@ -13443,11 +13604,172 @@ function createChatMessageTransformHandler(client, registry4, logger, config, pr
13443
13604
  return;
13444
13605
  }
13445
13606
  const lastUserMessage = getLastUserMessage(messages);
13446
- let state;
13607
+ const runPipeline = async (state) => {
13608
+ syncCompressPermissionState(state, config, hostPermissions, output.messages);
13609
+ if (state.isSubAgent && !config.allowSubAgents) {
13610
+ return;
13611
+ }
13612
+ stripHallucinations(output.messages);
13613
+ const dropReasoningModel = lastUserMessage?.info?.model;
13614
+ const reasoningConfig = applyCompressOverrides(
13615
+ config,
13616
+ dropReasoningModel?.providerID ?? state.modelProviderID,
13617
+ dropReasoningModel?.modelID ?? state.modelID
13618
+ ).compress.reasoning;
13619
+ if (reasoningConfig?.drop !== false) {
13620
+ const droppedReasoning = dropCompressReasoning(
13621
+ output.messages,
13622
+ reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13623
+ );
13624
+ if (droppedReasoning > 0) {
13625
+ logger.debug("compress.reasoning: dropped oversized reasoning parts", {
13626
+ dropped: droppedReasoning,
13627
+ threshold: reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13628
+ });
13629
+ }
13630
+ }
13631
+ ensureBuiltinFiltersRegistered();
13632
+ const effectiveLimit = resolveEffectiveContextLimit(state, config);
13633
+ applyMessageFilters(output.messages, config.messageFilters, logger, {
13634
+ sessionId: state.sessionId ?? "",
13635
+ isSubAgent: state.isSubAgent,
13636
+ modelContextLimit: effectiveLimit?.limit
13637
+ });
13638
+ cacheSystemPromptTokens(state, output.messages);
13639
+ assignMessageRefs(state, output.messages);
13640
+ const imagesConfig = config.compress.images ?? DEFAULT_COMPRESS_IMAGES;
13641
+ if (imagesConfig.enabled) {
13642
+ const archivedImages = archiveSessionImages(
13643
+ state,
13644
+ output.messages,
13645
+ imagesConfig,
13646
+ logger
13647
+ );
13648
+ if (archivedImages > 0) {
13649
+ saveSessionState(state, logger).catch(() => {
13650
+ });
13651
+ }
13652
+ pruneImageArchive(state, imagesConfig, logger);
13653
+ }
13654
+ const activeBlockCountBefore = state.prune.messages.activeBlockIds.size;
13655
+ const compressionStateChanged = syncCompressionBlocks(state, logger, output.messages);
13656
+ if (compressionStateChanged || state.prune.messages.activeBlockIds.size !== activeBlockCountBefore) {
13657
+ saveSessionState(state, logger).catch(() => {
13658
+ });
13659
+ }
13660
+ syncToolCache(state, config, logger, output.messages);
13661
+ buildToolIdList(state, output.messages);
13662
+ const batchResult = runBatchCleanup(state, config, logger, output.messages);
13663
+ if (batchResult.mergedCount > 0) {
13664
+ saveSessionState(state, logger).catch(() => {
13665
+ });
13666
+ }
13667
+ const prePruneTokens = getCurrentTokenUsage(state, output.messages);
13668
+ const candidateMessages = config.compress.candidates === true ? output.messages.slice() : void 0;
13669
+ prune(state, logger, config, output.messages);
13670
+ hideConsumedCompressCalls(state, output.messages);
13671
+ assignMessageRefs(state, output.messages);
13672
+ const compressionPriorities = buildPriorityMap(config, state, output.messages);
13673
+ prompts.reload();
13674
+ injectCompressNudges(
13675
+ state,
13676
+ config,
13677
+ logger,
13678
+ output.messages,
13679
+ prompts.getRuntimePrompts(),
13680
+ compressionPriorities,
13681
+ config.debug ? (text) => {
13682
+ logger.debug(`[ACP Debug] Nudge injected:
13683
+ ${text}`);
13684
+ client.tui.showToast({
13685
+ body: {
13686
+ title: "ACP: Nudge Injected",
13687
+ message: text.slice(0, 500),
13688
+ variant: "info",
13689
+ duration: 5e3
13690
+ }
13691
+ }).catch(() => {
13692
+ });
13693
+ } : void 0,
13694
+ prePruneTokens,
13695
+ candidateMessages
13696
+ );
13697
+ const emergencyTruncationEnabled = applyCompressOverrides(
13698
+ config,
13699
+ dropReasoningModel?.providerID ?? state.modelProviderID,
13700
+ dropReasoningModel?.modelID ?? state.modelID
13701
+ ).compress.emergencyTruncation;
13702
+ if (emergencyTruncationEnabled === true) {
13703
+ applyStickyTruncations(state, output.messages, logger);
13704
+ const toolOutputsBefore = snapshotToolOutputs(output.messages);
13705
+ truncateLargeToolOutputs(
13706
+ state,
13707
+ config,
13708
+ logger,
13709
+ output.messages.filter((message) => !isSyntheticMessage(message))
13710
+ );
13711
+ enforceContextBudget(state, config, logger, output.messages);
13712
+ const frozenCount = recordStickyTruncations(
13713
+ state,
13714
+ output.messages,
13715
+ toolOutputsBefore,
13716
+ logger
13717
+ );
13718
+ if (frozenCount > 0) {
13719
+ saveSessionState(state, logger).catch(() => {
13720
+ });
13721
+ }
13722
+ }
13723
+ injectMessageIds(state, config, output.messages, compressionPriorities);
13724
+ hideFailedCompressCalls(output.messages);
13725
+ stripStaleMetadata(output.messages);
13726
+ dropEmptyMessages(output.messages);
13727
+ const smartPlanEnabled = applyCompressOverrides(
13728
+ config,
13729
+ state.modelProviderID,
13730
+ state.modelID
13731
+ ).compress.smartPlanRequired;
13732
+ if (state.sessionId && smartPlanEnabled === true) {
13733
+ recordVisibleMessages(state.sessionId, output.messages);
13734
+ }
13735
+ const postTokens = getCurrentTokenUsage(state, output.messages);
13736
+ if (postTokens !== void 0 && effectiveLimit) {
13737
+ const budget = effectiveLimit.limit - (state.systemPromptTokens ?? 0) - OUTPUT_RESERVE_TOKENS;
13738
+ if (postTokens > budget) {
13739
+ logger.error(
13740
+ "ACP hard guard: context exceeds model budget after in-flight reduction",
13741
+ {
13742
+ session: state.sessionId,
13743
+ postTokens,
13744
+ budget,
13745
+ contextLimit: effectiveLimit.limit,
13746
+ contextLimitSource: effectiveLimit.source,
13747
+ hint: "request will likely be rejected; run /compact or start a new session"
13748
+ }
13749
+ );
13750
+ }
13751
+ }
13752
+ logger.info("Chat transform complete", {
13753
+ session: state.sessionId,
13754
+ model: state.modelID,
13755
+ messages: output.messages.length,
13756
+ prePruneTokens,
13757
+ postTokens,
13758
+ contextLimit: effectiveLimit?.limit,
13759
+ contextLimitSource: effectiveLimit?.source,
13760
+ usagePct: postTokens !== void 0 && effectiveLimit ? `${(postTokens / effectiveLimit.limit * 100).toFixed(1)}%` : void 0,
13761
+ nudged: state.nudges.shouldInjectThisTurn
13762
+ });
13763
+ if (state.sessionId) {
13764
+ await logger.saveContext(state.sessionId, output.messages);
13765
+ }
13766
+ };
13447
13767
  if (!lastUserMessage) {
13448
- state = createSessionState();
13449
- } else {
13450
- state = await registry4.getOrCreate(
13768
+ await runPipeline(createSessionState());
13769
+ return;
13770
+ }
13771
+ await registry4.withSessionGuard(lastUserMessage.info.sessionID, async () => {
13772
+ const state = await registry4.getOrCreate(
13451
13773
  client,
13452
13774
  lastUserMessage.info.sessionID,
13453
13775
  messages,
@@ -13504,146 +13826,8 @@ function createChatMessageTransformHandler(client, registry4, logger, config, pr
13504
13826
  }
13505
13827
  );
13506
13828
  }
13507
- }
13508
- syncCompressPermissionState(state, config, hostPermissions, output.messages);
13509
- if (state.isSubAgent && !config.allowSubAgents) {
13510
- return;
13511
- }
13512
- stripHallucinations(output.messages);
13513
- const dropReasoningModel = lastUserMessage?.info?.model;
13514
- const reasoningConfig = applyCompressOverrides(
13515
- config,
13516
- dropReasoningModel?.providerID ?? state.modelProviderID,
13517
- dropReasoningModel?.modelID ?? state.modelID
13518
- ).compress.reasoning;
13519
- if (reasoningConfig?.drop !== false) {
13520
- const droppedReasoning = dropCompressReasoning(
13521
- output.messages,
13522
- reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13523
- );
13524
- if (droppedReasoning > 0) {
13525
- logger.debug("compress.reasoning: dropped oversized reasoning parts", {
13526
- dropped: droppedReasoning,
13527
- threshold: reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13528
- });
13529
- }
13530
- }
13531
- ensureBuiltinFiltersRegistered();
13532
- const effectiveLimit = resolveEffectiveContextLimit(state, config);
13533
- applyMessageFilters(output.messages, config.messageFilters, logger, {
13534
- sessionId: state.sessionId ?? "",
13535
- isSubAgent: state.isSubAgent,
13536
- modelContextLimit: effectiveLimit?.limit
13537
- });
13538
- cacheSystemPromptTokens(state, output.messages);
13539
- assignMessageRefs(state, output.messages);
13540
- const imagesConfig = config.compress.images ?? DEFAULT_COMPRESS_IMAGES;
13541
- if (imagesConfig.enabled) {
13542
- const archivedImages = archiveSessionImages(
13543
- state,
13544
- output.messages,
13545
- imagesConfig,
13546
- logger
13547
- );
13548
- if (archivedImages > 0) {
13549
- saveSessionState(state, logger).catch(() => {
13550
- });
13551
- }
13552
- pruneImageArchive(state, imagesConfig, logger);
13553
- }
13554
- const activeBlockCountBefore = state.prune.messages.activeBlockIds.size;
13555
- const compressionStateChanged = syncCompressionBlocks(state, logger, output.messages);
13556
- if (compressionStateChanged || state.prune.messages.activeBlockIds.size !== activeBlockCountBefore) {
13557
- saveSessionState(state, logger).catch(() => {
13558
- });
13559
- }
13560
- syncToolCache(state, config, logger, output.messages);
13561
- buildToolIdList(state, output.messages);
13562
- const batchResult = runBatchCleanup(state, config, logger, output.messages);
13563
- if (batchResult.mergedCount > 0) {
13564
- saveSessionState(state, logger).catch(() => {
13565
- });
13566
- }
13567
- const prePruneTokens = getCurrentTokenUsage(state, output.messages);
13568
- const candidateMessages = config.compress.candidates === true ? output.messages.slice() : void 0;
13569
- prune(state, logger, config, output.messages);
13570
- hideConsumedCompressCalls(state, output.messages);
13571
- assignMessageRefs(state, output.messages);
13572
- const compressionPriorities = buildPriorityMap(config, state, output.messages);
13573
- prompts.reload();
13574
- injectCompressNudges(
13575
- state,
13576
- config,
13577
- logger,
13578
- output.messages,
13579
- prompts.getRuntimePrompts(),
13580
- compressionPriorities,
13581
- config.debug ? (text) => {
13582
- logger.debug(`[ACP Debug] Nudge injected:
13583
- ${text}`);
13584
- client.tui.showToast({
13585
- body: {
13586
- title: "ACP: Nudge Injected",
13587
- message: text.slice(0, 500),
13588
- variant: "info",
13589
- duration: 5e3
13590
- }
13591
- }).catch(() => {
13592
- });
13593
- } : void 0,
13594
- prePruneTokens,
13595
- candidateMessages
13596
- );
13597
- truncateLargeToolOutputs(
13598
- state,
13599
- config,
13600
- logger,
13601
- output.messages.filter((message) => !isSyntheticMessage(message))
13602
- );
13603
- enforceContextBudget(state, config, logger, output.messages);
13604
- injectMessageIds(state, config, output.messages, compressionPriorities);
13605
- hideFailedCompressCalls(output.messages);
13606
- stripStaleMetadata(output.messages);
13607
- dropEmptyMessages(output.messages);
13608
- const smartPlanEnabled = applyCompressOverrides(
13609
- config,
13610
- state.modelProviderID,
13611
- state.modelID
13612
- ).compress.smartPlanRequired;
13613
- if (state.sessionId && smartPlanEnabled === true) {
13614
- recordVisibleMessages(state.sessionId, output.messages);
13615
- }
13616
- const postTokens = getCurrentTokenUsage(state, output.messages);
13617
- if (postTokens !== void 0 && effectiveLimit) {
13618
- const budget = effectiveLimit.limit - (state.systemPromptTokens ?? 0) - OUTPUT_RESERVE_TOKENS;
13619
- if (postTokens > budget) {
13620
- logger.error(
13621
- "ACP hard guard: context exceeds model budget after in-flight reduction",
13622
- {
13623
- session: state.sessionId,
13624
- postTokens,
13625
- budget,
13626
- contextLimit: effectiveLimit.limit,
13627
- contextLimitSource: effectiveLimit.source,
13628
- hint: "request will likely be rejected; run /compact or start a new session"
13629
- }
13630
- );
13631
- }
13632
- }
13633
- logger.info("Chat transform complete", {
13634
- session: state.sessionId,
13635
- model: state.modelID,
13636
- messages: output.messages.length,
13637
- prePruneTokens,
13638
- postTokens,
13639
- contextLimit: effectiveLimit?.limit,
13640
- contextLimitSource: effectiveLimit?.source,
13641
- usagePct: postTokens !== void 0 && effectiveLimit ? `${(postTokens / effectiveLimit.limit * 100).toFixed(1)}%` : void 0,
13642
- nudged: state.nudges.shouldInjectThisTurn
13829
+ await runPipeline(state);
13643
13830
  });
13644
- if (state.sessionId) {
13645
- await logger.saveContext(state.sessionId, output.messages);
13646
- }
13647
13831
  };
13648
13832
  }
13649
13833
  function buildHelpText() {
@@ -13670,8 +13854,11 @@ function createCommandExecuteHandler(client, registry4, logger, config, workingD
13670
13854
  path: { id: input.sessionID }
13671
13855
  });
13672
13856
  const messages = filterMessages(messagesResponse.data || messagesResponse);
13673
- const state = await registry4.getOrCreate(client, input.sessionID, messages, config);
13674
- syncCompressPermissionState(state, config, hostPermissions, messages);
13857
+ const state = await registry4.withSessionGuard(input.sessionID, async () => {
13858
+ const s = await registry4.getOrCreate(client, input.sessionID, messages, config);
13859
+ syncCompressPermissionState(s, config, hostPermissions, messages);
13860
+ return s;
13861
+ });
13675
13862
  const commandCtx = {
13676
13863
  client,
13677
13864
  state,
@@ -13775,18 +13962,27 @@ function createEventHandler(registry4, logger) {
13775
13962
  callId: part.callID,
13776
13963
  durationMs
13777
13964
  });
13965
+ const settles = [];
13778
13966
  for (const state of registry4.all()) {
13779
- const updates = applyPendingCompressionDurations(state);
13780
- if (updates > 0) {
13781
- await saveSessionState(state, logger);
13782
- logger.info("Attached compression time to blocks", {
13783
- messageID: part.messageID,
13784
- callID: part.callID,
13785
- blocks: updates,
13786
- durationMs
13787
- });
13967
+ if (!state.sessionId) {
13968
+ continue;
13788
13969
  }
13970
+ settles.push(
13971
+ registry4.withSessionGuard(state.sessionId, async () => {
13972
+ const updates = applyPendingCompressionDurations(state);
13973
+ if (updates > 0) {
13974
+ await saveSessionState(state, logger);
13975
+ logger.info("Attached compression time to blocks", {
13976
+ messageID: part.messageID,
13977
+ callID: part.callID,
13978
+ blocks: updates,
13979
+ durationMs
13980
+ });
13981
+ }
13982
+ })
13983
+ );
13789
13984
  }
13985
+ await Promise.allSettled(settles);
13790
13986
  return;
13791
13987
  }
13792
13988
  if (part.state.status === "running") {
@@ -14039,7 +14235,7 @@ var server = (async (ctx) => {
14039
14235
  }
14040
14236
  const logger = new Logger(config.debug, config.debug ? "debug" : config.logLevel);
14041
14237
  logger.info("ACP plugin initialized", {
14042
- version: true ? "1.18.4" : "dev",
14238
+ version: true ? "1.18.5-pr.408.227" : "dev",
14043
14239
  workspace: ctx.directory,
14044
14240
  logLevel: logger.level,
14045
14241
  debug: config.debug,