@infituit/opencode-acp 2.0.0-alpha.2 → 2.0.0-alpha.3

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
@@ -11470,7 +11470,7 @@ import { writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
11470
11470
  import { join as join5 } from "path";
11471
11471
  import { existsSync as existsSync5 } from "fs";
11472
11472
  import { homedir as homedir3 } from "os";
11473
- var LOG_VERSION = true ? "2.0.0-alpha.2" : "dev";
11473
+ var LOG_VERSION = true ? "2.0.0-alpha.3" : "dev";
11474
11474
  var LEVEL_RANK = {
11475
11475
  debug: 10,
11476
11476
  info: 20,
@@ -11545,23 +11545,33 @@ var Logger = class {
11545
11545
  return "unknown";
11546
11546
  }
11547
11547
  }
11548
- async write(level, component, message, data) {
11548
+ async write(level, component, message, data, structured = false) {
11549
11549
  if (!this.shouldWrite(level.toLowerCase())) return;
11550
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
11550
11551
  try {
11551
11552
  await this.ensureLogDir();
11552
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
11553
- const dataStr = this.formatData(data);
11553
+ const dataStr = structured ? JSON.stringify(data) : this.formatData(data);
11554
11554
  const logLine = `${timestamp} ${level.padEnd(5)} ${component}: ${message}${dataStr ? " | " + dataStr : ""} | v=${LOG_VERSION}
11555
11555
  `;
11556
11556
  const dailyLogDir = join5(this.logDir, "daily");
11557
11557
  if (!existsSync5(dailyLogDir)) {
11558
11558
  await mkdir2(dailyLogDir, { recursive: true });
11559
11559
  }
11560
- const logFile = join5(dailyLogDir, `${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.log`);
11560
+ const logFile = join5(dailyLogDir, `${timestamp.split("T")[0]}.log`);
11561
11561
  await writeFile2(logFile, logLine, { flag: "a" });
11562
11562
  } catch (error) {
11563
11563
  }
11564
11564
  }
11565
+ /** One JSON payload on the existing daily sink; ordinary log formatting is unchanged. */
11566
+ diagnostic(event, data, level = "info") {
11567
+ return this.write(
11568
+ level.toUpperCase(),
11569
+ "diagnostics",
11570
+ event,
11571
+ { ...data, version: LOG_VERSION },
11572
+ true
11573
+ );
11574
+ }
11565
11575
  info(message, data) {
11566
11576
  if (!this.shouldWrite("info")) return;
11567
11577
  const component = this.getCallerFile(2);
@@ -11687,6 +11697,130 @@ var Logger = class {
11687
11697
  }
11688
11698
  };
11689
11699
 
11700
+ // src/diagnostics.ts
11701
+ import { AsyncLocalStorage } from "async_hooks";
11702
+ import { randomUUID } from "crypto";
11703
+ var requests = new AsyncLocalStorage();
11704
+ var instanceId = randomUUID();
11705
+ var sequence = 0;
11706
+ var milliseconds = (value) => Number(value.toFixed(3));
11707
+ var StageTimeline = class {
11708
+ constructor(stage, onStage) {
11709
+ this.stage = stage;
11710
+ this.onStage = onStage;
11711
+ onStage(stage);
11712
+ }
11713
+ stage;
11714
+ onStage;
11715
+ stageMs = {};
11716
+ checkpointAt = performance.now();
11717
+ ended = false;
11718
+ next(stage) {
11719
+ if (this.ended) return;
11720
+ const now = performance.now();
11721
+ this.stageMs[this.stage] = (this.stageMs[this.stage] ?? 0) + now - this.checkpointAt;
11722
+ this.checkpointAt = now;
11723
+ this.stage = stage;
11724
+ this.onStage(stage);
11725
+ }
11726
+ end() {
11727
+ if (this.ended) return;
11728
+ this.stageMs[this.stage] = (this.stageMs[this.stage] ?? 0) + performance.now() - this.checkpointAt;
11729
+ this.ended = true;
11730
+ }
11731
+ snapshot() {
11732
+ return Object.fromEntries(
11733
+ Object.entries(this.stageMs).map(([key, ms]) => [key, milliseconds(ms)])
11734
+ );
11735
+ }
11736
+ };
11737
+ var ContextDiagnostic = class {
11738
+ constructor(sessionId, logger) {
11739
+ this.sessionId = sessionId;
11740
+ this.logger = logger;
11741
+ }
11742
+ sessionId;
11743
+ logger;
11744
+ traceId = `${instanceId}-${++sequence}`;
11745
+ startedAt = performance.now();
11746
+ counts = {};
11747
+ lanes = /* @__PURE__ */ new Map();
11748
+ status = "ok";
11749
+ skipReason;
11750
+ failedStage;
11751
+ finished = false;
11752
+ timeline(lane, initialStage) {
11753
+ const timeline = new StageTimeline(initialStage, (stage) => {
11754
+ this.logger.debug("Context diagnostic stage", {
11755
+ sessionId: this.sessionId,
11756
+ traceId: this.traceId,
11757
+ lane,
11758
+ stage
11759
+ });
11760
+ });
11761
+ this.lanes.set(lane, timeline);
11762
+ return timeline;
11763
+ }
11764
+ skip(reason) {
11765
+ this.status = "skipped";
11766
+ this.skipReason = reason;
11767
+ }
11768
+ fail(lane) {
11769
+ this.status = "error";
11770
+ this.failedStage ??= `${lane}.${this.lanes.get(lane)?.stage ?? "unknown"}`;
11771
+ }
11772
+ get active() {
11773
+ return !this.finished;
11774
+ }
11775
+ finish() {
11776
+ if (this.finished) return;
11777
+ this.finished = true;
11778
+ for (const lane of this.lanes.values()) lane.end();
11779
+ try {
11780
+ void this.logger.diagnostic(
11781
+ "context",
11782
+ {
11783
+ schemaVersion: 1,
11784
+ instanceId,
11785
+ pid: process.pid,
11786
+ sessionId: this.sessionId,
11787
+ traceId: this.traceId,
11788
+ status: this.status,
11789
+ skipReason: this.skipReason,
11790
+ failedStage: this.failedStage,
11791
+ totalMs: milliseconds(performance.now() - this.startedAt),
11792
+ counts: this.counts,
11793
+ stageMs: Object.fromEntries(
11794
+ [...this.lanes].map(([name, lane]) => [name, lane.snapshot()])
11795
+ )
11796
+ },
11797
+ this.status === "error" ? "error" : "info"
11798
+ )?.catch(() => {
11799
+ });
11800
+ } catch {
11801
+ }
11802
+ }
11803
+ };
11804
+ function currentDiagnostic() {
11805
+ const request = requests.getStore();
11806
+ return request?.active ? request : void 0;
11807
+ }
11808
+ async function diagnoseContext(logger, sessionId, callback) {
11809
+ if (logger.level === "silent") return callback(void 0);
11810
+ const diagnostic = new ContextDiagnostic(sessionId, logger);
11811
+ return requests.run(diagnostic, async () => {
11812
+ logger.debug("Context diagnostic start", { sessionId, traceId: diagnostic.traceId });
11813
+ try {
11814
+ return await callback(diagnostic);
11815
+ } catch (error) {
11816
+ diagnostic.fail("context");
11817
+ throw error;
11818
+ } finally {
11819
+ diagnostic.finish();
11820
+ }
11821
+ });
11822
+ }
11823
+
11690
11824
  // src/prompts/store.ts
11691
11825
  import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync3, statSync as statSync3 } from "fs";
11692
11826
  import { join as join6, dirname as dirname2 } from "path";
@@ -13643,229 +13777,270 @@ function createSystemPromptHandler(registry4, logger, config, prompts) {
13643
13777
  }
13644
13778
  function createChatMessageTransformHandler(client, registry4, logger, config, prompts, hostPermissions) {
13645
13779
  return async (input, output) => {
13646
- const receivedMessages = Array.isArray(output.messages) ? output.messages.length : 0;
13647
- const messages = filterMessagesInPlace(output.messages);
13648
- if (messages.length !== receivedMessages) {
13649
- logger.warn("Skipping messages with unexpected shape during chat transform", {
13650
- received: receivedMessages,
13651
- usable: messages.length
13652
- });
13653
- }
13654
- if (isInternalAgentRequest(messages)) {
13655
- logger.debug("Skipping message transform for internal agent request");
13656
- return;
13657
- }
13658
- const lastUserMessage = getLastUserMessage(messages);
13659
- let state;
13660
- if (!lastUserMessage) {
13661
- state = createSessionState();
13662
- } else {
13663
- state = await registry4.getOrCreate(
13664
- client,
13665
- lastUserMessage.info.sessionID,
13666
- messages,
13667
- config
13668
- );
13669
- const requestModel = lastUserMessage.info.model;
13670
- let requestModelLimit = registry4.resolveModelLimit(
13671
- requestModel?.providerID,
13672
- requestModel?.modelID
13673
- );
13674
- if (requestModelLimit === void 0 && requestModel?.providerID && requestModel?.modelID) {
13675
- requestModelLimit = await registry4.hydrateAndResolve(
13780
+ const diagnostic = currentDiagnostic();
13781
+ const timeline = diagnostic?.timeline("transform", "filterMessages");
13782
+ const checkpoint = (nextStage) => timeline?.next(nextStage);
13783
+ try {
13784
+ const receivedMessages = Array.isArray(output.messages) ? output.messages.length : 0;
13785
+ const messages = filterMessagesInPlace(output.messages);
13786
+ if (messages.length !== receivedMessages) {
13787
+ logger.warn("Skipping messages with unexpected shape during chat transform", {
13788
+ received: receivedMessages,
13789
+ usable: messages.length
13790
+ });
13791
+ }
13792
+ if (isInternalAgentRequest(messages)) {
13793
+ diagnostic?.skip("internal_agent");
13794
+ logger.debug("Skipping message transform for internal agent request");
13795
+ return;
13796
+ }
13797
+ checkpoint("resolveSession");
13798
+ const lastUserMessage = getLastUserMessage(messages);
13799
+ let state;
13800
+ if (!lastUserMessage) {
13801
+ state = createSessionState();
13802
+ } else {
13803
+ state = await registry4.getOrCreate(
13676
13804
  client,
13677
- requestModel.providerID,
13678
- requestModel.modelID
13805
+ lastUserMessage.info.sessionID,
13806
+ messages,
13807
+ config
13808
+ );
13809
+ checkpoint("resolveModel");
13810
+ const requestModel = lastUserMessage.info.model;
13811
+ let requestModelLimit = registry4.resolveModelLimit(
13812
+ requestModel?.providerID,
13813
+ requestModel?.modelID
13679
13814
  );
13815
+ if (requestModelLimit === void 0 && requestModel?.providerID && requestModel?.modelID) {
13816
+ requestModelLimit = await registry4.hydrateAndResolve(
13817
+ client,
13818
+ requestModel.providerID,
13819
+ requestModel.modelID
13820
+ );
13821
+ }
13822
+ const prevModelID = state.modelID;
13823
+ if (requestModelLimit !== void 0) {
13824
+ state.modelContextLimit = requestModelLimit;
13825
+ state.modelProviderID = requestModel?.providerID;
13826
+ state.modelID = requestModel?.modelID;
13827
+ } else if (
13828
+ // [FIX #312 fallback] Catalog miss: we cannot CORRECT the
13829
+ // limit, but we can tell when it belongs to a DIFFERENT model.
13830
+ // Invalidate instead of letting every percentage threshold
13831
+ // below run against the wrong window (#312's false positive).
13832
+ // States persisted before this identity pair existed carry no
13833
+ // identity and are treated as stale for the same reason.
13834
+ // Consumers already tolerate undefined — fresh sessions run
13835
+ // with it until the first system.transform sets the pair.
13836
+ requestModel?.providerID && requestModel?.modelID && state.modelContextLimit !== void 0 && (state.modelProviderID !== requestModel.providerID || state.modelID !== requestModel.modelID)
13837
+ ) {
13838
+ state.modelContextLimit = void 0;
13839
+ state.modelProviderID = requestModel.providerID;
13840
+ state.modelID = requestModel.modelID;
13841
+ }
13842
+ if (requestModel?.modelID && requestModel.modelID !== prevModelID) {
13843
+ logger.info("Model switched mid-session", {
13844
+ session: state.sessionId,
13845
+ from: prevModelID,
13846
+ to: requestModel.modelID,
13847
+ contextLimit: state.modelContextLimit
13848
+ });
13849
+ }
13850
+ checkpoint("updatePerTurnState");
13851
+ await updatePerTurnState(state, logger, messages);
13852
+ checkpoint("permissions");
13853
+ if (state.modelContextLimit === void 0 && !state.noContextLimitWarned && requestModel?.providerID && requestModel?.modelID && registry4.resolveModelLimit(requestModel.providerID, requestModel.modelID) === void 0) {
13854
+ state.noContextLimitWarned = true;
13855
+ logger.warn(
13856
+ 'Model reports no context window and the catalog has no entry for it; all percentage thresholds (min/max/emergency, GC) and the context-budget guard are disabled. Set the model limit in opencode.json (e.g. "limit": {"context": 262144, "output": 16384}) to enable them (also fixes the 32000 max_tokens fallback); an absolute compress.maxContextLimit in acp.jsonc only enables proactive nudges, not the guard.',
13857
+ {
13858
+ session: state.sessionId,
13859
+ model: `${requestModel.providerID}/${requestModel.modelID}`
13860
+ }
13861
+ );
13862
+ }
13680
13863
  }
13681
- const prevModelID = state.modelID;
13682
- if (requestModelLimit !== void 0) {
13683
- state.modelContextLimit = requestModelLimit;
13684
- state.modelProviderID = requestModel?.providerID;
13685
- state.modelID = requestModel?.modelID;
13686
- } else if (
13687
- // [FIX #312 fallback] Catalog miss: we cannot CORRECT the
13688
- // limit, but we can tell when it belongs to a DIFFERENT model.
13689
- // Invalidate instead of letting every percentage threshold
13690
- // below run against the wrong window (#312's false positive).
13691
- // States persisted before this identity pair existed carry no
13692
- // identity and are treated as stale for the same reason.
13693
- // Consumers already tolerate undefined — fresh sessions run
13694
- // with it until the first system.transform sets the pair.
13695
- requestModel?.providerID && requestModel?.modelID && state.modelContextLimit !== void 0 && (state.modelProviderID !== requestModel.providerID || state.modelID !== requestModel.modelID)
13696
- ) {
13697
- state.modelContextLimit = void 0;
13698
- state.modelProviderID = requestModel.providerID;
13699
- state.modelID = requestModel.modelID;
13700
- }
13701
- if (requestModel?.modelID && requestModel.modelID !== prevModelID) {
13702
- logger.info("Model switched mid-session", {
13703
- session: state.sessionId,
13704
- from: prevModelID,
13705
- to: requestModel.modelID,
13706
- contextLimit: state.modelContextLimit
13707
- });
13864
+ checkpoint("permissions");
13865
+ syncCompressPermissionState(state, config, hostPermissions, output.messages);
13866
+ if (diagnostic) {
13867
+ diagnostic.counts.blocks = state.prune.messages.blocksById.size;
13868
+ diagnostic.counts.activeBlocks = state.prune.messages.activeBlockIds.size;
13708
13869
  }
13709
- await updatePerTurnState(state, logger, messages);
13710
- if (state.modelContextLimit === void 0 && !state.noContextLimitWarned && requestModel?.providerID && requestModel?.modelID && registry4.resolveModelLimit(requestModel.providerID, requestModel.modelID) === void 0) {
13711
- state.noContextLimitWarned = true;
13712
- logger.warn(
13713
- 'Model reports no context window and the catalog has no entry for it; all percentage thresholds (min/max/emergency, GC) and the context-budget guard are disabled. Set the model limit in opencode.json (e.g. "limit": {"context": 262144, "output": 16384}) to enable them (also fixes the 32000 max_tokens fallback); an absolute compress.maxContextLimit in acp.jsonc only enables proactive nudges, not the guard.',
13714
- {
13715
- session: state.sessionId,
13716
- model: `${requestModel.providerID}/${requestModel.modelID}`
13717
- }
13870
+ if (state.isSubAgent && !config.allowSubAgents) {
13871
+ diagnostic?.skip("subagent_disabled");
13872
+ return;
13873
+ }
13874
+ checkpoint("stripHallucinations");
13875
+ stripHallucinations(output.messages);
13876
+ checkpoint("dropReasoning");
13877
+ const dropReasoningModel = lastUserMessage?.info?.model;
13878
+ const reasoningConfig = applyCompressOverrides(
13879
+ config,
13880
+ dropReasoningModel?.providerID ?? state.modelProviderID,
13881
+ dropReasoningModel?.modelID ?? state.modelID
13882
+ ).compress.reasoning;
13883
+ if (reasoningConfig?.drop !== false) {
13884
+ const droppedReasoning = dropCompressReasoning(
13885
+ output.messages,
13886
+ reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13718
13887
  );
13888
+ if (droppedReasoning > 0) {
13889
+ logger.debug("compress.reasoning: dropped oversized reasoning parts", {
13890
+ dropped: droppedReasoning,
13891
+ threshold: reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13892
+ });
13893
+ }
13719
13894
  }
13720
- }
13721
- syncCompressPermissionState(state, config, hostPermissions, output.messages);
13722
- if (state.isSubAgent && !config.allowSubAgents) {
13723
- return;
13724
- }
13725
- stripHallucinations(output.messages);
13726
- const dropReasoningModel = lastUserMessage?.info?.model;
13727
- const reasoningConfig = applyCompressOverrides(
13728
- config,
13729
- dropReasoningModel?.providerID ?? state.modelProviderID,
13730
- dropReasoningModel?.modelID ?? state.modelID
13731
- ).compress.reasoning;
13732
- if (reasoningConfig?.drop !== false) {
13733
- const droppedReasoning = dropCompressReasoning(
13734
- output.messages,
13735
- reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13736
- );
13737
- if (droppedReasoning > 0) {
13738
- logger.debug("compress.reasoning: dropped oversized reasoning parts", {
13739
- dropped: droppedReasoning,
13740
- threshold: reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13895
+ checkpoint("messageFilters");
13896
+ ensureBuiltinFiltersRegistered();
13897
+ const effectiveLimit = resolveEffectiveContextLimit(state, config);
13898
+ applyMessageFilters(output.messages, config.messageFilters, logger, {
13899
+ sessionId: state.sessionId ?? "",
13900
+ isSubAgent: state.isSubAgent,
13901
+ modelContextLimit: effectiveLimit?.limit
13902
+ });
13903
+ checkpoint("cacheSystemPromptTokens");
13904
+ cacheSystemPromptTokens(state, output.messages);
13905
+ checkpoint("messageRefsAndImages");
13906
+ assignMessageRefs(state, output.messages);
13907
+ const imagesConfig = config.compress.images ?? DEFAULT_COMPRESS_IMAGES;
13908
+ if (imagesConfig.enabled) {
13909
+ const archivedImages = archiveSessionImages(
13910
+ state,
13911
+ output.messages,
13912
+ imagesConfig,
13913
+ logger
13914
+ );
13915
+ if (archivedImages > 0) {
13916
+ saveSessionState(state, logger).catch(() => {
13917
+ });
13918
+ }
13919
+ pruneImageArchive(state, imagesConfig, logger);
13920
+ }
13921
+ checkpoint("syncCompressionBlocks");
13922
+ const activeBlockCountBefore = state.prune.messages.activeBlockIds.size;
13923
+ const compressionStateChanged = syncCompressionBlocks(state, logger, output.messages);
13924
+ if (compressionStateChanged || state.prune.messages.activeBlockIds.size !== activeBlockCountBefore) {
13925
+ saveSessionState(state, logger).catch(() => {
13741
13926
  });
13742
13927
  }
13743
- }
13744
- ensureBuiltinFiltersRegistered();
13745
- const effectiveLimit = resolveEffectiveContextLimit(state, config);
13746
- applyMessageFilters(output.messages, config.messageFilters, logger, {
13747
- sessionId: state.sessionId ?? "",
13748
- isSubAgent: state.isSubAgent,
13749
- modelContextLimit: effectiveLimit?.limit
13750
- });
13751
- cacheSystemPromptTokens(state, output.messages);
13752
- assignMessageRefs(state, output.messages);
13753
- const imagesConfig = config.compress.images ?? DEFAULT_COMPRESS_IMAGES;
13754
- if (imagesConfig.enabled) {
13755
- const archivedImages = archiveSessionImages(
13756
- state,
13757
- output.messages,
13758
- imagesConfig,
13759
- logger
13760
- );
13761
- if (archivedImages > 0) {
13928
+ checkpoint("syncToolCache");
13929
+ syncToolCache(state, config, logger, output.messages);
13930
+ checkpoint("batchCleanup");
13931
+ buildToolIdList(state, output.messages);
13932
+ const batchResult = runBatchCleanup(state, config, logger, output.messages);
13933
+ if (batchResult.mergedCount > 0) {
13762
13934
  saveSessionState(state, logger).catch(() => {
13763
13935
  });
13764
13936
  }
13765
- pruneImageArchive(state, imagesConfig, logger);
13766
- }
13767
- const activeBlockCountBefore = state.prune.messages.activeBlockIds.size;
13768
- const compressionStateChanged = syncCompressionBlocks(state, logger, output.messages);
13769
- if (compressionStateChanged || state.prune.messages.activeBlockIds.size !== activeBlockCountBefore) {
13770
- saveSessionState(state, logger).catch(() => {
13771
- });
13772
- }
13773
- syncToolCache(state, config, logger, output.messages);
13774
- buildToolIdList(state, output.messages);
13775
- const batchResult = runBatchCleanup(state, config, logger, output.messages);
13776
- if (batchResult.mergedCount > 0) {
13777
- saveSessionState(state, logger).catch(() => {
13778
- });
13779
- }
13780
- const prePruneTokens = getCurrentTokenUsage(state, output.messages);
13781
- const candidateMessages = config.compress.candidates === true ? output.messages.slice() : void 0;
13782
- prune(state, logger, config, output.messages);
13783
- hideConsumedCompressCalls(state, output.messages);
13784
- assignMessageRefs(state, output.messages);
13785
- const compressionPriorities = buildPriorityMap(config, state, output.messages);
13786
- prompts.reload();
13787
- injectCompressNudges(
13788
- state,
13789
- config,
13790
- logger,
13791
- output.messages,
13792
- prompts.getRuntimePrompts(),
13793
- compressionPriorities,
13794
- config.debug ? (text) => {
13795
- logger.debug(`[ACP Debug] Nudge injected:
13796
- ${text}`);
13797
- } : void 0,
13798
- prePruneTokens,
13799
- candidateMessages
13800
- );
13801
- const emergencyTruncationEnabled = applyCompressOverrides(
13802
- config,
13803
- dropReasoningModel?.providerID ?? state.modelProviderID,
13804
- dropReasoningModel?.modelID ?? state.modelID
13805
- ).compress.emergencyTruncation;
13806
- if (emergencyTruncationEnabled === true) {
13807
- applyStickyTruncations(state, output.messages, logger);
13808
- const toolOutputsBefore = snapshotToolOutputs(output.messages);
13809
- truncateLargeToolOutputs(
13937
+ checkpoint("prePruneTokens");
13938
+ const prePruneTokens = getCurrentTokenUsage(state, output.messages);
13939
+ checkpoint("prune");
13940
+ const candidateMessages = config.compress.candidates === true ? output.messages.slice() : void 0;
13941
+ prune(state, logger, config, output.messages);
13942
+ checkpoint("compressNudges");
13943
+ hideConsumedCompressCalls(state, output.messages);
13944
+ assignMessageRefs(state, output.messages);
13945
+ const compressionPriorities = buildPriorityMap(config, state, output.messages);
13946
+ prompts.reload();
13947
+ injectCompressNudges(
13810
13948
  state,
13811
13949
  config,
13812
13950
  logger,
13813
- output.messages.filter((message) => !isSyntheticMessage(message))
13814
- );
13815
- enforceContextBudget(state, config, logger, output.messages);
13816
- const frozenCount = recordStickyTruncations(
13817
- state,
13818
13951
  output.messages,
13819
- toolOutputsBefore,
13820
- logger
13952
+ prompts.getRuntimePrompts(),
13953
+ compressionPriorities,
13954
+ config.debug ? (text) => {
13955
+ logger.debug(`[ACP Debug] Nudge injected:
13956
+ ${text}`);
13957
+ } : void 0,
13958
+ prePruneTokens,
13959
+ candidateMessages
13821
13960
  );
13822
- if (frozenCount > 0) {
13823
- saveSessionState(state, logger).catch(() => {
13824
- });
13825
- }
13826
- }
13827
- injectMessageIds(state, config, output.messages, compressionPriorities);
13828
- hideFailedCompressCalls(output.messages);
13829
- stripStaleMetadata(output.messages);
13830
- dropEmptyMessages(output.messages);
13831
- const smartPlanEnabled = applyCompressOverrides(
13832
- config,
13833
- state.modelProviderID,
13834
- state.modelID
13835
- ).compress.smartPlanRequired;
13836
- if (state.sessionId && smartPlanEnabled === true) {
13837
- recordVisibleMessages(state.sessionId, output.messages);
13838
- }
13839
- const postTokens = getCurrentTokenUsage(state, output.messages);
13840
- if (postTokens !== void 0 && effectiveLimit) {
13841
- const budget = effectiveLimit.limit - (state.systemPromptTokens ?? 0) - OUTPUT_RESERVE_TOKENS;
13842
- if (postTokens > budget) {
13843
- logger.error(
13844
- "ACP hard guard: context exceeds model budget after in-flight reduction",
13845
- {
13846
- session: state.sessionId,
13847
- postTokens,
13848
- budget,
13849
- contextLimit: effectiveLimit.limit,
13850
- contextLimitSource: effectiveLimit.source,
13851
- hint: "request will likely be rejected; run /compact or start a new session"
13852
- }
13961
+ checkpoint("emergencyTruncation");
13962
+ const emergencyTruncationEnabled = applyCompressOverrides(
13963
+ config,
13964
+ dropReasoningModel?.providerID ?? state.modelProviderID,
13965
+ dropReasoningModel?.modelID ?? state.modelID
13966
+ ).compress.emergencyTruncation;
13967
+ if (emergencyTruncationEnabled === true) {
13968
+ applyStickyTruncations(state, output.messages, logger);
13969
+ const toolOutputsBefore = snapshotToolOutputs(output.messages);
13970
+ truncateLargeToolOutputs(
13971
+ state,
13972
+ config,
13973
+ logger,
13974
+ output.messages.filter((message) => !isSyntheticMessage(message))
13853
13975
  );
13976
+ enforceContextBudget(state, config, logger, output.messages);
13977
+ const frozenCount = recordStickyTruncations(
13978
+ state,
13979
+ output.messages,
13980
+ toolOutputsBefore,
13981
+ logger
13982
+ );
13983
+ if (frozenCount > 0) {
13984
+ saveSessionState(state, logger).catch(() => {
13985
+ });
13986
+ }
13854
13987
  }
13855
- }
13856
- logger.info("Chat transform complete", {
13857
- session: state.sessionId,
13858
- model: state.modelID,
13859
- messages: output.messages.length,
13860
- prePruneTokens,
13861
- postTokens,
13862
- contextLimit: effectiveLimit?.limit,
13863
- contextLimitSource: effectiveLimit?.source,
13864
- usagePct: postTokens !== void 0 && effectiveLimit ? `${(postTokens / effectiveLimit.limit * 100).toFixed(1)}%` : void 0,
13865
- nudged: state.nudges.shouldInjectThisTurn
13866
- });
13867
- if (state.sessionId) {
13868
- await logger.saveContext(state.sessionId, output.messages);
13988
+ checkpoint("finalizeMessages");
13989
+ injectMessageIds(state, config, output.messages, compressionPriorities);
13990
+ hideFailedCompressCalls(output.messages);
13991
+ stripStaleMetadata(output.messages);
13992
+ dropEmptyMessages(output.messages);
13993
+ const smartPlanEnabled = applyCompressOverrides(
13994
+ config,
13995
+ state.modelProviderID,
13996
+ state.modelID
13997
+ ).compress.smartPlanRequired;
13998
+ if (state.sessionId && smartPlanEnabled === true) {
13999
+ recordVisibleMessages(state.sessionId, output.messages);
14000
+ }
14001
+ checkpoint("postTokens");
14002
+ const postTokens = getCurrentTokenUsage(state, output.messages);
14003
+ checkpoint("budgetGuard");
14004
+ if (postTokens !== void 0 && effectiveLimit) {
14005
+ const budget = effectiveLimit.limit - (state.systemPromptTokens ?? 0) - OUTPUT_RESERVE_TOKENS;
14006
+ if (postTokens > budget) {
14007
+ logger.error(
14008
+ "ACP hard guard: context exceeds model budget after in-flight reduction",
14009
+ {
14010
+ session: state.sessionId,
14011
+ postTokens,
14012
+ budget,
14013
+ contextLimit: effectiveLimit.limit,
14014
+ contextLimitSource: effectiveLimit.source,
14015
+ hint: "request will likely be rejected; run /compact or start a new session"
14016
+ }
14017
+ );
14018
+ }
14019
+ }
14020
+ logger.info("Chat transform complete", {
14021
+ session: state.sessionId,
14022
+ model: state.modelID,
14023
+ messages: output.messages.length,
14024
+ prePruneTokens,
14025
+ postTokens,
14026
+ contextLimit: effectiveLimit?.limit,
14027
+ contextLimitSource: effectiveLimit?.source,
14028
+ usagePct: postTokens !== void 0 && effectiveLimit ? `${(postTokens / effectiveLimit.limit * 100).toFixed(1)}%` : void 0,
14029
+ nudged: state.nudges.shouldInjectThisTurn
14030
+ });
14031
+ checkpoint("saveContext");
14032
+ if (diagnostic) {
14033
+ diagnostic.counts.blocks = state.prune.messages.blocksById.size;
14034
+ diagnostic.counts.activeBlocks = state.prune.messages.activeBlockIds.size;
14035
+ }
14036
+ if (state.sessionId) {
14037
+ await logger.saveContext(state.sessionId, output.messages);
14038
+ }
14039
+ } catch (error) {
14040
+ diagnostic?.fail("transform");
14041
+ throw error;
14042
+ } finally {
14043
+ timeline?.end();
13869
14044
  }
13870
14045
  };
13871
14046
  }
@@ -14334,32 +14509,45 @@ var AcpV2Plugin = Plugin.define({
14334
14509
  );
14335
14510
  const transformSystem = createSystemPromptHandler(registry4, logger, config, prompts);
14336
14511
  await ctx.session.hook("context", async (event) => {
14337
- const messages = await fetchV2SessionMessages(ctx, event.sessionID);
14338
- if (messages.length === 0) return;
14339
- const lastUser = [...messages].reverse().find((message) => message.info.role === "user");
14340
- if (lastUser?.info.role === "user") {
14341
- lastUser.info.agent = event.agent;
14342
- lastUser.info.model = {
14343
- providerID: event.model.providerID,
14344
- modelID: event.model.id
14512
+ await diagnoseContext(logger, event.sessionID, async (diagnostic) => {
14513
+ const timeline = diagnostic?.timeline("context", "fetchSessionMessages");
14514
+ const checkpoint = (stage) => timeline?.next(stage);
14515
+ const messages = await fetchV2SessionMessages(ctx, event.sessionID);
14516
+ checkpoint("prepareMessages");
14517
+ if (diagnostic) diagnostic.counts.inputMessages = messages.length;
14518
+ if (messages.length === 0) {
14519
+ diagnostic?.skip("empty_history");
14520
+ return;
14521
+ }
14522
+ const lastUser = [...messages].reverse().find((message) => message.info.role === "user");
14523
+ if (lastUser?.info.role === "user") {
14524
+ lastUser.info.agent = event.agent;
14525
+ lastUser.info.model = {
14526
+ providerID: event.model.providerID,
14527
+ modelID: event.model.id
14528
+ };
14529
+ lastUser.info.providerID = event.model.providerID;
14530
+ lastUser.info.modelID = event.model.id;
14531
+ }
14532
+ const output = { messages };
14533
+ checkpoint("transformMessages");
14534
+ await transformMessages({}, output);
14535
+ if (diagnostic) diagnostic.counts.outputMessages = output.messages.length;
14536
+ checkpoint("convertRequestMessages");
14537
+ event.messages = toV2RequestMessages(output.messages);
14538
+ checkpoint("transformSystem");
14539
+ const systemOutput = {
14540
+ system: event.system.map((part) => part.text)
14345
14541
  };
14346
- lastUser.info.providerID = event.model.providerID;
14347
- lastUser.info.modelID = event.model.id;
14348
- }
14349
- const output = { messages };
14350
- await transformMessages({}, output);
14351
- event.messages = toV2RequestMessages(output.messages);
14352
- const systemOutput = {
14353
- system: event.system.map((part) => part.text)
14354
- };
14355
- await transformSystem(
14356
- {
14357
- sessionID: event.sessionID,
14358
- model: asV2Model(event.model)
14359
- },
14360
- systemOutput
14361
- );
14362
- event.system = systemOutput.system.map((text) => ({ type: "text", text }));
14542
+ await transformSystem(
14543
+ {
14544
+ sessionID: event.sessionID,
14545
+ model: asV2Model(event.model)
14546
+ },
14547
+ systemOutput
14548
+ );
14549
+ event.system = systemOutput.system.map((text) => ({ type: "text", text }));
14550
+ });
14363
14551
  });
14364
14552
  const abort = new AbortController();
14365
14553
  const eventHandler = createEventHandler(registry4, logger);