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

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
@@ -2209,7 +2209,7 @@ function resolveToolContext(factoryCtx, sessionID) {
2209
2209
  };
2210
2210
  }
2211
2211
 
2212
- // src/token-utils.ts
2212
+ // src/context-usage.ts
2213
2213
  import * as _anthropicTokenizer from "@anthropic-ai/tokenizer";
2214
2214
 
2215
2215
  // src/messages/shape.ts
@@ -2353,7 +2353,7 @@ function isProtectedUserMessage(_config, message) {
2353
2353
  return false;
2354
2354
  }
2355
2355
 
2356
- // src/token-utils.ts
2356
+ // src/context-usage.ts
2357
2357
  var anthropicCountTokens = _anthropicTokenizer.countTokens ?? _anthropicTokenizer.default?.countTokens;
2358
2358
  function getCurrentTokenUsage(state, messages) {
2359
2359
  for (let i = messages.length - 1; i >= 0; i--) {
@@ -2790,7 +2790,6 @@ function getTierTokenUsage(state) {
2790
2790
  return { tier1Tokens, tier2Tokens, tier3Tokens };
2791
2791
  }
2792
2792
  function resetOnCompaction(state) {
2793
- state.toolParameters.clear();
2794
2793
  state.nudges = {
2795
2794
  contextLimitAnchors: /* @__PURE__ */ new Set(),
2796
2795
  turnNudgeAnchors: /* @__PURE__ */ new Set(),
@@ -5236,7 +5235,6 @@ function createSessionState() {
5236
5235
  startsByCallId: /* @__PURE__ */ new Map(),
5237
5236
  pendingByCallId: /* @__PURE__ */ new Map()
5238
5237
  },
5239
- toolParameters: /* @__PURE__ */ new Map(),
5240
5238
  toolIdList: [],
5241
5239
  messageIds: {
5242
5240
  byRawId: /* @__PURE__ */ new Map(),
@@ -5282,7 +5280,6 @@ function resetSessionState(state) {
5282
5280
  pruneTokenCounter: 0,
5283
5281
  totalPruneTokens: 0
5284
5282
  };
5285
- state.toolParameters.clear();
5286
5283
  state.toolIdList = [];
5287
5284
  state.messageIds = {
5288
5285
  byRawId: /* @__PURE__ */ new Map(),
@@ -5448,67 +5445,6 @@ async function ensureSessionInitialized(client, state, sessionId, logger, messag
5448
5445
  await saveSessionState(state, logger);
5449
5446
  }
5450
5447
 
5451
- // src/state/tool-cache.ts
5452
- var MAX_TOOL_CACHE_SIZE = 1e3;
5453
- function syncToolCache(state, config, logger, messages) {
5454
- try {
5455
- logger.info("Syncing tool parameters from OpenCode messages");
5456
- let turnCounter = 0;
5457
- for (const msg of messages) {
5458
- if (isMessageCompacted(state, msg)) {
5459
- continue;
5460
- }
5461
- const parts = Array.isArray(msg.parts) ? msg.parts : [];
5462
- for (const part of parts) {
5463
- if (part.type === "step-start") {
5464
- turnCounter++;
5465
- continue;
5466
- }
5467
- if (part.type !== "tool" || !part.callID) {
5468
- continue;
5469
- }
5470
- if (state.toolParameters.has(part.callID)) {
5471
- continue;
5472
- }
5473
- const contents = extractToolContent(part);
5474
- const rawLength = contents.reduce((sum, s) => sum + (s?.length ?? 0), 0);
5475
- const tokenCount = Math.round(rawLength / 4);
5476
- state.toolParameters.set(part.callID, {
5477
- tool: part.tool,
5478
- parameters: part.state?.input ?? {},
5479
- status: part.state.status,
5480
- error: part.state.status === "error" ? part.state.error : void 0,
5481
- turn: turnCounter,
5482
- tokenCount
5483
- });
5484
- logger.info(
5485
- `Cached tool id: ${part.callID} (turn ${turnCounter}${tokenCount !== void 0 ? `, ${tokenCount} tokens` : ""})`
5486
- );
5487
- }
5488
- }
5489
- logger.info(
5490
- `Synced cache - size: ${state.toolParameters.size}, currentTurn: ${state.currentTurn}`
5491
- );
5492
- trimToolParametersCache(state);
5493
- } catch (error) {
5494
- logger.warn("Failed to sync tool parameters from OpenCode", {
5495
- error: error instanceof Error ? error.message : String(error)
5496
- });
5497
- }
5498
- }
5499
- function trimToolParametersCache(state) {
5500
- if (state.toolParameters.size <= MAX_TOOL_CACHE_SIZE) {
5501
- return;
5502
- }
5503
- const keysToRemove = Array.from(state.toolParameters.keys()).slice(
5504
- 0,
5505
- state.toolParameters.size - MAX_TOOL_CACHE_SIZE
5506
- );
5507
- for (const key of keysToRemove) {
5508
- state.toolParameters.delete(key);
5509
- }
5510
- }
5511
-
5512
5448
  // src/ui/utils.ts
5513
5449
  function formatAge(createdAt2) {
5514
5450
  const elapsed = Date.now() - createdAt2;
@@ -11470,7 +11406,7 @@ import { writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
11470
11406
  import { join as join5 } from "path";
11471
11407
  import { existsSync as existsSync5 } from "fs";
11472
11408
  import { homedir as homedir3 } from "os";
11473
- var LOG_VERSION = true ? "2.0.0-alpha.3" : "dev";
11409
+ var LOG_VERSION = true ? "2.0.0-alpha.5" : "dev";
11474
11410
  var LEVEL_RANK = {
11475
11411
  debug: 10,
11476
11412
  info: 20,
@@ -12403,6 +12339,65 @@ function renderSystemPrompt(prompts, protectedToolsExtension, subagent) {
12403
12339
  return [prompts.system.trim(), ...extensions].filter(Boolean).join("\n\n").replace(/\n([ \t]*\n)+/g, "\n\n").trim();
12404
12340
  }
12405
12341
 
12342
+ // src/v2/hooks/system.ts
12343
+ var INTERNAL_AGENT_SIGNATURES = [
12344
+ "You are a title generator",
12345
+ "You are a helpful AI assistant tasked with summarizing conversations",
12346
+ "You are an anchored context summarization assistant for coding sessions",
12347
+ "Summarize what was done in this conversation"
12348
+ ];
12349
+ function createSystemPromptHandler(registry4, logger, config, prompts) {
12350
+ return async (input, output) => {
12351
+ registry4.recordModelLimit(
12352
+ input.model?.providerID,
12353
+ input.model?.id,
12354
+ input.model?.limit?.context
12355
+ );
12356
+ const state = input.sessionID ? registry4.get(input.sessionID) : void 0;
12357
+ if (!state || state.isSubAgent && !config.allowSubAgents) {
12358
+ return;
12359
+ }
12360
+ const systemText = output.system.join("\n");
12361
+ if (INTERNAL_AGENT_SIGNATURES.some((sig) => systemText.includes(sig))) {
12362
+ logger.info("Skipping ACP system prompt injection for internal agent");
12363
+ return;
12364
+ }
12365
+ if (input.model?.limit?.context) {
12366
+ const limit = input.model.limit.context;
12367
+ const providerID = input.model?.providerID;
12368
+ const modelID = input.model?.id;
12369
+ const changed = state.modelContextLimit !== limit || providerID !== void 0 && state.modelProviderID !== providerID || modelID !== void 0 && state.modelID !== modelID;
12370
+ state.modelContextLimit = limit;
12371
+ if (providerID !== void 0) {
12372
+ state.modelProviderID = providerID;
12373
+ }
12374
+ if (modelID !== void 0) {
12375
+ state.modelID = modelID;
12376
+ }
12377
+ if (changed) {
12378
+ saveSessionState(state, logger).catch(() => {
12379
+ });
12380
+ }
12381
+ }
12382
+ const effectivePermission = compressPermission(state, config);
12383
+ if (effectivePermission === "deny") {
12384
+ return;
12385
+ }
12386
+ prompts.reload();
12387
+ const runtimePrompts = prompts.getRuntimePrompts();
12388
+ const newPrompt = renderSystemPrompt(
12389
+ runtimePrompts,
12390
+ buildProtectedToolsExtension(config.compress.protectedTools),
12391
+ state.isSubAgent && config.allowSubAgents
12392
+ );
12393
+ if (output.system.length > 0) {
12394
+ output.system[output.system.length - 1] += "\n\n" + newPrompt;
12395
+ } else {
12396
+ output.system.push(newPrompt);
12397
+ }
12398
+ };
12399
+ }
12400
+
12406
12401
  // src/messages/truncate-tools.ts
12407
12402
  var TRUNCATION_MARKER = "[truncated for context space";
12408
12403
  var MIN_OUTPUT_TOKENS = 1e3;
@@ -12718,1332 +12713,1275 @@ function enforceContextBudget(state, config, logger, messages) {
12718
12713
  };
12719
12714
  }
12720
12715
 
12721
- // src/commands/context.ts
12722
- function analyzeTokens(state, messages) {
12723
- const breakdown = {
12724
- system: 0,
12725
- user: 0,
12726
- assistant: 0,
12727
- tools: 0,
12728
- toolCount: 0,
12729
- toolsInContextCount: 0,
12730
- prunedTokens: state.stats.totalPruneTokens,
12731
- prunedToolCount: 0,
12732
- prunedMessageCount: 0,
12733
- total: 0
12716
+ // src/messages/filter/registry.ts
12717
+ var registry3 = /* @__PURE__ */ new Map();
12718
+ function registerMessageFilter(filter) {
12719
+ const existing = registry3.get(filter.name);
12720
+ if (existing && existing.version !== filter.version) {
12721
+ throw new Error(
12722
+ `Message filter "${filter.name}" already registered with version ${existing.version}, cannot register version ${filter.version}. Use a different name or bump version.`
12723
+ );
12724
+ }
12725
+ registry3.set(filter.name, filter);
12726
+ }
12727
+ function getMessageFilter(name) {
12728
+ return registry3.get(name);
12729
+ }
12730
+ function listMessageFilters() {
12731
+ return Array.from(registry3.values());
12732
+ }
12733
+
12734
+ // src/messages/filter/apply.ts
12735
+ function applyMessageFilters(messages, config, logger, ctx) {
12736
+ if (!config?.enabled) {
12737
+ return { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
12738
+ }
12739
+ const allFilters = listMessageFilters().filter((f) => {
12740
+ const fc = config.filters?.[f.name];
12741
+ return fc?.enabled !== false;
12742
+ });
12743
+ if (allFilters.length === 0) {
12744
+ return { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
12745
+ }
12746
+ const result = { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
12747
+ const total = messages.length;
12748
+ const warnedFilters = /* @__PURE__ */ new Set();
12749
+ const buildCtx = (text, role, i) => ({
12750
+ text,
12751
+ role,
12752
+ sessionId: ctx.sessionId,
12753
+ isSubAgent: ctx.isSubAgent,
12754
+ messageIndex: i,
12755
+ totalMessages: total,
12756
+ modelContextLimit: ctx.modelContextLimit
12757
+ });
12758
+ const applyDecision = (part, decision, filterName, i, originalText) => {
12759
+ result.partsFiltered++;
12760
+ if (decision.action === "drop") {
12761
+ part.text = "";
12762
+ result.partsDropped++;
12763
+ if (decision.reason) {
12764
+ logger.debug("Message filter dropped text", {
12765
+ filter: filterName,
12766
+ reason: decision.reason,
12767
+ messageIndex: i,
12768
+ originalLength: originalText.length
12769
+ });
12770
+ }
12771
+ return "";
12772
+ }
12773
+ if (decision.action === "modify" && decision.text !== void 0) {
12774
+ part.text = decision.text;
12775
+ result.partsModified++;
12776
+ if (decision.reason) {
12777
+ logger.debug("Message filter modified text", {
12778
+ filter: filterName,
12779
+ reason: decision.reason,
12780
+ messageIndex: i,
12781
+ originalLength: originalText.length,
12782
+ newLength: decision.text.length
12783
+ });
12784
+ }
12785
+ return decision.text;
12786
+ }
12787
+ return originalText;
12734
12788
  };
12735
- let firstAssistant;
12736
- for (const msg of messages) {
12737
- if (msg.info.role === "assistant") {
12738
- const assistantInfo = msg.info;
12739
- if (assistantInfo.tokens?.input > 0 || assistantInfo.tokens?.cache?.read > 0 || assistantInfo.tokens?.cache?.write > 0) {
12740
- firstAssistant = assistantInfo;
12741
- break;
12789
+ const immediateFilters = allFilters.filter((f) => !f.keepLastOnly);
12790
+ for (let i = 0; i < messages.length; i++) {
12791
+ const msg = messages[i];
12792
+ const role = msg.info.role ?? "unknown";
12793
+ for (const part of msg.parts ?? []) {
12794
+ const text = part.text;
12795
+ if (typeof text !== "string" || text.length === 0) continue;
12796
+ let current = text;
12797
+ const filterCtx = buildCtx(current, role, i);
12798
+ filterCtx.toolName = part.tool;
12799
+ for (const filter of immediateFilters) {
12800
+ let decision;
12801
+ try {
12802
+ decision = filter.filter(filterCtx);
12803
+ } catch (err) {
12804
+ if (!warnedFilters.has(filter.name)) {
12805
+ warnedFilters.add(filter.name);
12806
+ logger.warn("Message filter threw error", {
12807
+ filter: filter.name,
12808
+ error: err instanceof Error ? err.message : String(err),
12809
+ messageIndex: i
12810
+ });
12811
+ }
12812
+ continue;
12813
+ }
12814
+ if (decision.action === "keep") continue;
12815
+ current = applyDecision(part, decision, filter.name, i, current);
12816
+ filterCtx.text = current;
12742
12817
  }
12743
12818
  }
12744
12819
  }
12745
- let lastAssistant;
12746
- for (let i = messages.length - 1; i >= 0; i--) {
12747
- const msg = messages[i];
12748
- if (msg.info.role === "assistant") {
12749
- const assistantInfo = msg.info;
12750
- if (assistantInfo.tokens?.output > 0) {
12751
- lastAssistant = assistantInfo;
12752
- break;
12820
+ const keepLastFilters = allFilters.filter((f) => f.keepLastOnly);
12821
+ for (const filter of keepLastFilters) {
12822
+ const fcKeepLast = config.filters?.[filter.name]?.keepLast;
12823
+ const keepCount = Math.max(1, fcKeepLast ?? filter.keepLast ?? 1);
12824
+ let kept = 0;
12825
+ for (let i = messages.length - 1; i >= 0; i--) {
12826
+ const msg = messages[i];
12827
+ const role = msg.info.role ?? "unknown";
12828
+ const parts = msg.parts ?? [];
12829
+ for (let p = parts.length - 1; p >= 0; p--) {
12830
+ const part = parts[p];
12831
+ const text = part.text;
12832
+ if (typeof text !== "string" || text.length === 0) continue;
12833
+ const filterCtx = buildCtx(text, role, i);
12834
+ filterCtx.toolName = part.tool;
12835
+ let decision;
12836
+ try {
12837
+ decision = filter.filter(filterCtx);
12838
+ } catch {
12839
+ continue;
12840
+ }
12841
+ if (decision.action !== "drop" && decision.action !== "modify") continue;
12842
+ if (kept < keepCount) {
12843
+ kept++;
12844
+ } else {
12845
+ applyDecision(part, decision, filter.name, i, text);
12846
+ }
12753
12847
  }
12754
12848
  }
12755
12849
  }
12756
- const apiInput = lastAssistant?.tokens?.input || 0;
12757
- const apiOutput = lastAssistant?.tokens?.output || 0;
12758
- const apiReasoning = lastAssistant?.tokens?.reasoning || 0;
12759
- const apiCacheRead = lastAssistant?.tokens?.cache?.read || 0;
12760
- const apiCacheWrite = lastAssistant?.tokens?.cache?.write || 0;
12761
- breakdown.total = apiInput + apiOutput + apiReasoning + apiCacheRead + apiCacheWrite;
12762
- const userTextParts = [];
12763
- const toolInputParts = [];
12764
- const toolOutputParts = [];
12765
- let firstUserText = "";
12766
- let foundFirstUser = false;
12767
- const allToolIds = /* @__PURE__ */ new Set();
12768
- const activeToolIds = /* @__PURE__ */ new Set();
12769
- const prunedToolIds = /* @__PURE__ */ new Set();
12770
- const allMessageIds = /* @__PURE__ */ new Set();
12771
- for (const msg of messages) {
12772
- allMessageIds.add(msg.info.id);
12773
- const parts = Array.isArray(msg.parts) ? msg.parts : [];
12774
- const isCompacted = isMessageCompacted(state, msg);
12775
- const pruneEntry = state.prune.messages.byMessageId.get(msg.info.id);
12776
- const isMessagePruned = !!pruneEntry && pruneEntry.activeBlockIds.length > 0;
12777
- const isIgnoredUser = isIgnoredUserMessage(msg);
12778
- for (const part of parts) {
12779
- if (part.type === "tool") {
12780
- const toolPart = part;
12781
- if (toolPart.callID) {
12782
- allToolIds.add(toolPart.callID);
12783
- if (!isCompacted) {
12784
- activeToolIds.add(toolPart.callID);
12785
- }
12786
- if (isMessagePruned) {
12787
- prunedToolIds.add(toolPart.callID);
12788
- }
12789
- }
12790
- if (!isCompacted) {
12791
- if (toolPart.state?.input) {
12792
- const inputStr = typeof toolPart.state.input === "string" ? toolPart.state.input : JSON.stringify(toolPart.state.input);
12793
- toolInputParts.push(inputStr);
12794
- }
12795
- const outputStr = extractCompletedToolOutput(toolPart);
12796
- if (outputStr !== void 0) {
12797
- toolOutputParts.push(outputStr);
12798
- }
12850
+ if (result.partsFiltered > 0) {
12851
+ logger.info("Message filters applied", {
12852
+ filtersRun: allFilters.length,
12853
+ partsFiltered: result.partsFiltered,
12854
+ partsDropped: result.partsDropped,
12855
+ partsModified: result.partsModified
12856
+ });
12857
+ }
12858
+ return result;
12859
+ }
12860
+
12861
+ // src/messages/filter/builtin/omo-system-reminder.ts
12862
+ var SYSTEM_REMINDER_OPEN = "<system-reminder>";
12863
+ var OMO_MARKER = "<!-- OMO_INTERNAL_INITIATOR -->";
12864
+ var PAIRED_BLOCK_RE = /<system-reminder>[\s\S]*?<\/system-reminder>\s*<!-- OMO_INTERNAL_INITIATOR -->/g;
12865
+ var LONE_REMINDER_RE = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
12866
+ var LONE_MARKER_RE = /<!-- OMO_INTERNAL_INITIATOR -->/g;
12867
+ var OMO_SYSTEM_REMINDER_FILTER = {
12868
+ name: "omo-system-reminder",
12869
+ version: "1.3.0",
12870
+ description: "Keep recent OMO <system-reminder> messages; for older ones, strip blocks but preserve user content",
12871
+ keepLastOnly: true,
12872
+ keepLast: 2,
12873
+ filter(ctx) {
12874
+ if (ctx.role !== "user") return { action: "keep" };
12875
+ if (!ctx.text.includes(SYSTEM_REMINDER_OPEN) && !ctx.text.includes(OMO_MARKER)) {
12876
+ return { action: "keep" };
12877
+ }
12878
+ let modified = ctx.text;
12879
+ let removedBlocks = 0;
12880
+ modified = modified.replace(PAIRED_BLOCK_RE, () => {
12881
+ removedBlocks++;
12882
+ return "";
12883
+ });
12884
+ modified = modified.replace(LONE_REMINDER_RE, () => {
12885
+ removedBlocks++;
12886
+ return "";
12887
+ });
12888
+ modified = modified.replace(LONE_MARKER_RE, "");
12889
+ modified = modified.replace(/\n{3,}/g, "\n\n").trim();
12890
+ if (modified.length === 0) {
12891
+ return { action: "drop", reason: `Pure OMO system-reminder (${removedBlocks} block(s), no user content)` };
12892
+ }
12893
+ return {
12894
+ action: "modify",
12895
+ text: modified,
12896
+ reason: `Stripped ${removedBlocks} OMO system-reminder block(s), preserved user content (${modified.length} chars)`
12897
+ };
12898
+ }
12899
+ };
12900
+
12901
+ // src/messages/filter/builtin/omo-todo-continuation.ts
12902
+ var TODO_MARKER = "[SYSTEM DIRECTIVE";
12903
+ var TODO_CONTINUATION = "TODO CONTINUATION";
12904
+ var OMO_TODO_FILTER = {
12905
+ name: "omo-todo-continuation",
12906
+ version: "1.0.0",
12907
+ description: "Keep only the latest OMO TODO CONTINUATION directive, drop earlier occurrences",
12908
+ keepLastOnly: true,
12909
+ filter(ctx) {
12910
+ if (ctx.role !== "user") return { action: "keep" };
12911
+ if (!ctx.text.includes(TODO_MARKER) || !ctx.text.includes(TODO_CONTINUATION)) {
12912
+ return { action: "keep" };
12913
+ }
12914
+ return { action: "drop", reason: "TODO CONTINUATION directive" };
12915
+ }
12916
+ };
12917
+
12918
+ // src/messages/filter/builtin/omo-context.ts
12919
+ var OMO_MARKER2 = "<!-- OMO_INTERNAL_INITIATOR -->";
12920
+ var OMO_CONTEXT_FILTER = {
12921
+ name: "omo-context",
12922
+ version: "1.0.0",
12923
+ description: "Keep only the latest OMO [CONTEXT] injection, drop earlier occurrences",
12924
+ keepLastOnly: true,
12925
+ filter(ctx) {
12926
+ if (ctx.role !== "user") return { action: "keep" };
12927
+ if (!ctx.text.includes(OMO_MARKER2)) return { action: "keep" };
12928
+ const stripped = ctx.text.trimStart();
12929
+ if (!stripped.startsWith("[CONTEXT]") && !stripped.startsWith("CONTEXT:")) {
12930
+ return { action: "keep" };
12931
+ }
12932
+ return { action: "drop", reason: "OMO context injection" };
12933
+ }
12934
+ };
12935
+
12936
+ // src/messages/filter/builtin/omo-task-directive.ts
12937
+ var OMO_MARKER3 = "<!-- OMO_INTERNAL_INITIATOR -->";
12938
+ var OMO_TASK_FILTER = {
12939
+ name: "omo-task-directive",
12940
+ version: "1.0.0",
12941
+ description: "Keep only the latest OMO TASK directive, drop earlier occurrences",
12942
+ keepLastOnly: true,
12943
+ filter(ctx) {
12944
+ if (ctx.role !== "user") return { action: "keep" };
12945
+ if (!ctx.text.includes(OMO_MARKER3)) return { action: "keep" };
12946
+ const stripped = ctx.text.trimStart();
12947
+ if (!stripped.startsWith("TASK:") && !stripped.startsWith("## TASK")) {
12948
+ return { action: "keep" };
12949
+ }
12950
+ return { action: "drop", reason: "OMO task directive" };
12951
+ }
12952
+ };
12953
+
12954
+ // src/messages/filter/builtin/omo-mode-injection.ts
12955
+ var XML_MODE_TAGS = [
12956
+ { open: "<hyperplan-ultrawork-mode>", close: "</hyperplan-ultrawork-mode>" },
12957
+ { open: "<ultrawork-mode>", close: "</ultrawork-mode>" }
12958
+ ];
12959
+ var BRACKET_MODE_PATTERNS = ["[search-mode]", "[analyze-mode]", "[ultrawork-mode]"];
12960
+ function stripLeadingModeInjections(text) {
12961
+ let current = text;
12962
+ let strippedAny = false;
12963
+ for (let iter = 0; iter < 5; iter++) {
12964
+ current = current.trimStart();
12965
+ let matched = false;
12966
+ for (const { open, close } of XML_MODE_TAGS) {
12967
+ if (current.startsWith(open)) {
12968
+ const closeIdx = current.indexOf(close);
12969
+ if (closeIdx !== -1) {
12970
+ current = current.slice(closeIdx + close.length);
12971
+ } else {
12972
+ current = current.slice(open.length);
12799
12973
  }
12800
- } else if (part.type === "text" && msg.info.role === "user" && !isCompacted && !isIgnoredUser) {
12801
- const textPart = part;
12802
- const text = textPart.text || "";
12803
- userTextParts.push(text);
12804
- if (!foundFirstUser) {
12805
- firstUserText += text;
12974
+ matched = true;
12975
+ break;
12976
+ }
12977
+ }
12978
+ if (!matched) {
12979
+ for (const pattern of BRACKET_MODE_PATTERNS) {
12980
+ if (current.startsWith(pattern)) {
12981
+ current = current.slice(pattern.length);
12982
+ matched = true;
12983
+ break;
12806
12984
  }
12807
12985
  }
12808
12986
  }
12809
- if (msg.info.role === "user" && !isIgnoredUser && !foundFirstUser) {
12810
- foundFirstUser = true;
12987
+ if (matched) {
12988
+ strippedAny = true;
12989
+ } else {
12990
+ break;
12811
12991
  }
12812
12992
  }
12813
- const toolsInContextCount = [...activeToolIds].filter((id) => !prunedToolIds.has(id)).length;
12814
- let prunedMessageCount = 0;
12815
- for (const [id, entry] of state.prune.messages.byMessageId) {
12816
- if (allMessageIds.has(id) && entry.activeBlockIds.length > 0) {
12817
- prunedMessageCount++;
12993
+ return strippedAny ? current.trim() : null;
12994
+ }
12995
+ var OMO_MODE_FILTER = {
12996
+ name: "omo-mode-injection",
12997
+ version: "1.1.0",
12998
+ description: "Strip OMO mode injection blocks (<ultrawork-mode>...</ultrawork-mode>, [search-mode], etc.) from user messages, preserving user content",
12999
+ filter(ctx) {
13000
+ if (ctx.role !== "user") return { action: "keep" };
13001
+ const remaining = stripLeadingModeInjections(ctx.text);
13002
+ if (remaining === null) return { action: "keep" };
13003
+ if (remaining.length === 0) {
13004
+ return { action: "drop", reason: "OMO mode injection (no user content after stripping)" };
12818
13005
  }
13006
+ return {
13007
+ action: "modify",
13008
+ text: remaining,
13009
+ reason: "Stripped OMO mode injection block(s), preserved user content"
13010
+ };
12819
13011
  }
12820
- breakdown.toolCount = allToolIds.size;
12821
- breakdown.toolsInContextCount = toolsInContextCount;
12822
- breakdown.prunedToolCount = prunedToolIds.size;
12823
- breakdown.prunedMessageCount = prunedMessageCount;
12824
- const firstUserTokens = countTokens2(firstUserText);
12825
- breakdown.user = countTokens2(userTextParts.join("\n"));
12826
- const toolInputTokens = countTokens2(toolInputParts.join("\n"));
12827
- const toolOutputTokens = countTokens2(toolOutputParts.join("\n"));
12828
- if (firstAssistant) {
12829
- const firstInput = (firstAssistant.tokens?.input || 0) + (firstAssistant.tokens?.cache?.read || 0) + (firstAssistant.tokens?.cache?.write || 0);
12830
- breakdown.system = Math.max(0, firstInput - firstUserTokens);
13012
+ };
13013
+
13014
+ // src/messages/filter/builtin/index.ts
13015
+ var BUILTIN_FILTERS = [
13016
+ OMO_SYSTEM_REMINDER_FILTER,
13017
+ OMO_TODO_FILTER,
13018
+ OMO_CONTEXT_FILTER,
13019
+ OMO_TASK_FILTER,
13020
+ OMO_MODE_FILTER
13021
+ ];
13022
+ function ensureBuiltinFiltersRegistered() {
13023
+ for (const filter of BUILTIN_FILTERS) {
13024
+ if (!getMessageFilter(filter.name)) {
13025
+ registerMessageFilter(filter);
13026
+ }
12831
13027
  }
12832
- breakdown.tools = toolInputTokens + toolOutputTokens;
12833
- breakdown.assistant = Math.max(
12834
- 0,
12835
- breakdown.total - breakdown.system - breakdown.user - breakdown.tools
12836
- );
12837
- return breakdown;
12838
13028
  }
12839
- function createBar(value, maxValue, width, char = "\u2588") {
12840
- if (maxValue === 0) return "";
12841
- const filled = Math.round(value / maxValue * width);
12842
- const bar = char.repeat(Math.max(0, filled));
12843
- return bar;
13029
+
13030
+ // src/gc/merge.ts
13031
+ function collectActiveOldGenBlocks(state, maxOldGenSummaryLength) {
13032
+ const blocks = [];
13033
+ const ids = Array.from(state.prune.messages.activeBlockIds).sort((a, b) => a - b);
13034
+ for (const id of ids) {
13035
+ const block = state.prune.messages.blocksById.get(id);
13036
+ if (!block || !block.active) continue;
13037
+ if (block.generation === "old" || block.generation === void 0 || block.summary.length > maxOldGenSummaryLength) {
13038
+ blocks.push(block);
13039
+ }
13040
+ }
13041
+ return blocks;
12844
13042
  }
12845
- function formatContextMessage(breakdown) {
12846
- const lines = [];
12847
- const barWidth = 30;
12848
- const toolsLabel = `Tools (${breakdown.toolsInContextCount})`;
12849
- const categories = [
12850
- { label: "System", value: breakdown.system, char: "\u2588" },
12851
- { label: "User", value: breakdown.user, char: "\u2593" },
12852
- { label: "Assistant", value: breakdown.assistant, char: "\u2592" },
12853
- { label: toolsLabel, value: breakdown.tools, char: "\u2591" }
12854
- ];
12855
- const maxLabelLen = Math.max(...categories.map((c) => c.label.length));
12856
- lines.push("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E");
12857
- lines.push("\u2502 ACP Context Analysis \u2502");
12858
- lines.push("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");
12859
- lines.push("");
12860
- lines.push("Session Context Breakdown:");
12861
- lines.push("\u2500".repeat(60));
12862
- lines.push("");
12863
- for (const cat of categories) {
12864
- const bar = createBar(cat.value, breakdown.total, barWidth, cat.char);
12865
- const percentage = breakdown.total > 0 ? (cat.value / breakdown.total * 100).toFixed(1) : "0.0";
12866
- const labelWithPct = `${cat.label.padEnd(maxLabelLen)} ${percentage.padStart(5)}% `;
12867
- const valueStr = formatTokenCount(cat.value).padStart(13);
12868
- lines.push(`${labelWithPct}\u2502${bar.padEnd(barWidth)}\u2502${valueStr}`);
12869
- }
12870
- lines.push("");
12871
- lines.push("\u2500".repeat(60));
12872
- lines.push("");
12873
- lines.push("Summary:");
12874
- if (breakdown.prunedTokens > 0) {
12875
- const withoutPruning = breakdown.total + breakdown.prunedTokens;
12876
- const pruned = [];
12877
- if (breakdown.prunedToolCount > 0) pruned.push(`${breakdown.prunedToolCount} tools`);
12878
- if (breakdown.prunedMessageCount > 0)
12879
- pruned.push(`${breakdown.prunedMessageCount} messages`);
12880
- lines.push(
12881
- ` Pruned: ${pruned.join(", ")} (~${formatTokenCount(breakdown.prunedTokens)})`
12882
- );
12883
- lines.push(` Current context: ~${formatTokenCount(breakdown.total)}`);
12884
- lines.push(` Without ACP: ~${formatTokenCount(withoutPruning)}`);
12885
- } else {
12886
- lines.push(` Current context: ~${formatTokenCount(breakdown.total)}`);
12887
- }
12888
- lines.push("");
12889
- return lines.join("\n");
12890
- }
12891
- async function handleContextCommand(ctx) {
12892
- const { client, state, logger, sessionId, messages } = ctx;
12893
- const breakdown = analyzeTokens(state, messages);
12894
- const message = formatContextMessage(breakdown);
12895
- const params = getCurrentParams(state, messages, logger);
12896
- await sendIgnoredMessage(client, sessionId, message, params, logger);
12897
- }
12898
-
12899
- // src/commands/stats.ts
12900
- async function handleStatsCommand(ctx) {
12901
- const report = buildStatusReport(
12902
- { state: ctx.state, config: ctx.config },
12903
- ctx.messages
12904
- );
12905
- const text = `[ACP Status]
12906
- ${report}`;
12907
- await sendIgnoredMessage(
12908
- ctx.client,
12909
- ctx.sessionId,
12910
- text,
12911
- {
12912
- providerId: ctx.userInfo?.providerId,
12913
- modelId: ctx.userInfo?.modelId,
12914
- agent: ctx.userInfo?.agent,
12915
- variant: ctx.userInfo?.variant
12916
- },
12917
- ctx.logger
12918
- );
12919
- }
12920
-
12921
- // src/commands/export.ts
12922
- import * as fs2 from "fs/promises";
12923
- import { existsSync as existsSync7 } from "fs";
12924
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join7, resolve } from "path";
12925
- var ALL_TIERS = [1, 2, 3];
12926
- var TIER_NAMES = {
12927
- 1: "Tier 1 \u2014 Capture",
12928
- 2: "Tier 2 \u2014 Distilled",
12929
- 3: "Tier 3 \u2014 Condensed"
12930
- };
12931
- function parseExportArgs(rawArgs) {
12932
- const options = {
12933
- outputPath: "",
12934
- // "" sentinel => default path resolved later
12935
- tiers: /* @__PURE__ */ new Set(),
12936
- includeMetadata: true,
12937
- append: false
12938
- };
12939
- const tokens = tokenize2(rawArgs);
12940
- let i = 0;
12941
- while (i < tokens.length) {
12942
- const tok = tokens[i];
12943
- const [flag, inlineValue] = splitFlag(tok);
12944
- switch (flag) {
12945
- case "--output":
12946
- case "-o": {
12947
- const value = inlineValue ?? tokens[i + 1];
12948
- if (value === void 0) {
12949
- throw new Error("--output requires a path (use `-` for stdout)");
12950
- }
12951
- options.outputPath = value;
12952
- i += inlineValue !== void 0 ? 1 : 2;
12953
- break;
12954
- }
12955
- case "--tier":
12956
- case "-t": {
12957
- const value = inlineValue ?? tokens[i + 1];
12958
- if (value === void 0) {
12959
- throw new Error("--tier requires a value (e.g. t2,t3 or all)");
12960
- }
12961
- options.tiers = parseTiers(value);
12962
- i += inlineValue !== void 0 ? 1 : 2;
12963
- break;
12964
- }
12965
- case "--no-metadata":
12966
- if (inlineValue !== void 0) {
12967
- throw new Error("--no-metadata does not take a value");
12968
- }
12969
- options.includeMetadata = false;
12970
- i += 1;
12971
- break;
12972
- case "--metadata":
12973
- if (inlineValue !== void 0) {
12974
- throw new Error("--metadata does not take a value");
12975
- }
12976
- options.includeMetadata = true;
12977
- i += 1;
12978
- break;
12979
- case "--append":
12980
- if (inlineValue !== void 0) {
12981
- throw new Error("--append does not take a value");
12982
- }
12983
- options.append = true;
12984
- i += 1;
12985
- break;
12986
- case "--stdout":
12987
- if (inlineValue !== void 0) {
12988
- throw new Error("--stdout does not take a value");
12989
- }
12990
- options.outputPath = "-";
12991
- i += 1;
12992
- break;
12993
- default:
12994
- throw new Error(
12995
- `Unknown flag: ${tok}. Supported: --output, --tier, --no-metadata, --append, --stdout.`
12996
- );
12997
- }
13043
+ function extractSummaryBody(summary) {
13044
+ let body = summary;
13045
+ const headerPrefix = COMPRESSED_BLOCK_HEADER + "\n";
13046
+ if (body.startsWith(headerPrefix)) {
13047
+ body = body.slice(headerPrefix.length);
12998
13048
  }
12999
- return options;
13049
+ body = body.replace(/\n]*>b\d+<\/acp-message-id>$/, "");
13050
+ return body.trim();
13000
13051
  }
13001
- function tokenize2(input) {
13002
- const tokens = [];
13003
- const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
13004
- let m;
13005
- while ((m = re.exec(input)) !== null) {
13006
- tokens.push(m[1] ?? m[2] ?? m[3]);
13052
+ function truncateMergedSummary(merged, maxLength) {
13053
+ if (merged.length <= maxLength) return merged;
13054
+ const blocks = merged.split("\n---\n");
13055
+ const headers = blocks.map((b) => b.split("\n")[0] ?? "").filter((h) => h.trim().length > 0);
13056
+ const marker = "\n...\n[merged and truncated by batch cleanup]";
13057
+ const budget = Math.max(0, maxLength - marker.length);
13058
+ const headerJoin = headers.join("\n");
13059
+ if (headerJoin.length <= budget) {
13060
+ return headerJoin + marker;
13007
13061
  }
13008
- return tokens;
13009
- }
13010
- function splitFlag(tok) {
13011
- const eq = tok.indexOf("=");
13012
- if (eq === -1) return [tok, void 0];
13013
- return [tok.slice(0, eq), tok.slice(eq + 1)];
13062
+ return headerJoin.slice(0, budget) + marker;
13014
13063
  }
13015
- function parseTiers(raw) {
13016
- const lower = raw.trim().toLowerCase();
13017
- if (lower === "all") return new Set(ALL_TIERS);
13018
- const parts = lower.split(",").map((p) => p.trim()).filter((p) => p.length > 0);
13019
- const result = /* @__PURE__ */ new Set();
13020
- for (const part of parts) {
13021
- const digits = part.replace(/^t/i, "");
13022
- const n = Number(digits);
13023
- if (!Number.isInteger(n) || n < 1 || n > 3) {
13024
- throw new Error(
13025
- `Invalid tier "${part}". Expected t1, t2, t3, a combination (t2,t3), or "all".`
13026
- );
13064
+ function mergeMarkedBlocks(state, markedIds, maxMergedLength) {
13065
+ const sortedIds = [...new Set(markedIds)].filter(
13066
+ (id) => Number.isInteger(id) && id > 0
13067
+ ).sort((a, b) => a - b);
13068
+ const sourceBlocks = [];
13069
+ for (const id of sortedIds) {
13070
+ const block = state.prune.messages.blocksById.get(id);
13071
+ if (!block || !block.active) continue;
13072
+ if (!sourceBlocks.some((b) => b.blockId === id)) {
13073
+ sourceBlocks.push(block);
13027
13074
  }
13028
- result.add(n);
13029
- }
13030
- if (result.size === 0) {
13031
- throw new Error(`Invalid tier "${raw}". Expected t1, t2, t3, or "all".`);
13032
13075
  }
13033
- return result;
13034
- }
13035
- function resolveDefaultOutputPath(sessionId, cwd2) {
13036
- const short = (sessionId || "session").slice(0, 8);
13037
- return join7(cwd2, ".opencode", `acp-export-${short}.md`);
13038
- }
13039
- function formatTokens2(n) {
13040
- if (!Number.isFinite(n) || n <= 0) return "0";
13041
- return n >= 1e3 ? `${(n / 1e3).toFixed(1)}K` : String(n);
13042
- }
13043
- function effectiveTokens(block) {
13044
- return block.effectiveCompressedTokens ?? block.compressedTokens ?? 0;
13045
- }
13046
- function collectActiveBlocks(state) {
13047
- const msgState = state.prune.messages;
13048
- const blocks = [];
13049
- for (const id of msgState.activeBlockIds) {
13050
- const block = msgState.blocksById.get(id);
13051
- if (block && block.active) {
13052
- blocks.push(block);
13053
- }
13076
+ if (sourceBlocks.length < 2) {
13077
+ return { mergedCount: 0, savedTokens: 0 };
13054
13078
  }
13055
- return blocks;
13056
- }
13057
- function filterByTier(blocks, tiers) {
13058
- if (tiers.size === 0) return blocks;
13059
- return blocks.filter((b) => tiers.has(b.tier ?? 1));
13060
- }
13061
- function tokenSpans(blocks) {
13062
- return {
13063
- effective: blocks.reduce((s, b) => s + effectiveTokens(b), 0),
13064
- summary: blocks.reduce((s, b) => s + (b.summaryTokens || 0), 0)
13065
- };
13066
- }
13067
- function tierCounts(blocks) {
13068
- const counts = {};
13069
- for (const b of blocks) {
13070
- const t = b.tier ?? 1;
13071
- counts[t] = (counts[t] || 0) + 1;
13079
+ const messagesState = state.prune.messages;
13080
+ const newBlockId = allocateBlockId(state);
13081
+ const newRunId = allocateRunId(state);
13082
+ const bodies = sourceBlocks.map((block) => extractSummaryBody(block.summary));
13083
+ const mergedRaw = bodies.join("\n---\n");
13084
+ const mergedBody = truncateMergedSummary(mergedRaw, maxMergedLength);
13085
+ const newSummary = wrapCompressedSummary(newBlockId, mergedBody);
13086
+ const newSummaryTokens = countTokens2(newSummary);
13087
+ const oldest = sourceBlocks[0];
13088
+ const newest = sourceBlocks[sourceBlocks.length - 1];
13089
+ const effectiveMessageIds = /* @__PURE__ */ new Set();
13090
+ const effectiveToolIds = /* @__PURE__ */ new Set();
13091
+ for (const block of sourceBlocks) {
13092
+ for (const id of block.effectiveMessageIds) effectiveMessageIds.add(id);
13093
+ for (const id of block.effectiveToolIds) effectiveToolIds.add(id);
13072
13094
  }
13073
- return ALL_TIERS.filter((t) => counts[t]).map((t) => `T${t}: ${counts[t]}`).join(", ");
13074
- }
13075
- function renderExportMarkdown(params) {
13076
- const { sessionId, generatedAt, blocks, tiers, includeMetadata } = params;
13077
- const out = [];
13078
- const tierFilterLabel = tiers.size === 0 ? "all" : ALL_TIERS.filter((t) => tiers.has(t)).map((t) => `T${t}`).join(", ");
13079
- out.push("# ACP Session Export");
13080
- out.push("");
13081
- out.push(`- **Session**: \`${(sessionId || "unknown").slice(0, 16)}\``);
13082
- out.push(`- **Generated**: ${generatedAt.toISOString()}`);
13083
- out.push(`- **Blocks exported**: ${blocks.length}`);
13084
- const breakdown = tierCounts(blocks);
13085
- if (breakdown) {
13086
- out.push(` - ${breakdown}`);
13087
- }
13088
- out.push(`- **Tiers**: ${tierFilterLabel}`);
13089
- const span = tokenSpans(blocks);
13090
- if (blocks.length > 0) {
13091
- out.push(
13092
- `- **Coverage**: ${formatTokens2(span.effective)} original \u2192 ${formatTokens2(span.summary)} summary`
13093
- );
13094
- }
13095
- out.push("");
13096
- out.push("---");
13097
- out.push("");
13098
- if (blocks.length === 0) {
13099
- out.push("_No active compression blocks match the selected tiers._");
13100
- out.push("");
13101
- out.push(
13102
- "Tip: run `/acp export --tier all` to include every active tier, or trigger a compression first."
13103
- );
13104
- return out.join("\n");
13095
+ const sourceIds = sourceBlocks.map((b) => b.blockId);
13096
+ const createdAt2 = Date.now();
13097
+ const mergedBlock = {
13098
+ blockId: newBlockId,
13099
+ runId: newRunId,
13100
+ active: true,
13101
+ deactivatedByUser: false,
13102
+ compressedTokens: 0,
13103
+ summaryTokens: newSummaryTokens,
13104
+ durationMs: 0,
13105
+ mode: "range",
13106
+ topic: "Batch merge cleanup",
13107
+ batchTopic: "Batch merge cleanup",
13108
+ startId: oldest.startId,
13109
+ endId: newest.endId,
13110
+ anchorMessageId: oldest.anchorMessageId,
13111
+ compressMessageId: "",
13112
+ compressCallId: void 0,
13113
+ includedBlockIds: [...sourceIds],
13114
+ consumedBlockIds: [...sourceIds],
13115
+ parentBlockIds: [],
13116
+ directMessageIds: [],
13117
+ directToolIds: [],
13118
+ effectiveMessageIds: [...effectiveMessageIds],
13119
+ effectiveToolIds: [...effectiveToolIds],
13120
+ createdAt: createdAt2,
13121
+ summary: newSummary,
13122
+ survivedCount: 0,
13123
+ generation: "old"
13124
+ };
13125
+ const now = Date.now();
13126
+ for (const block of sourceBlocks) {
13127
+ block.active = false;
13128
+ block.deactivatedAt = now;
13129
+ block.deactivatedByBlockId = newBlockId;
13130
+ if (!block.parentBlockIds.includes(newBlockId)) {
13131
+ block.parentBlockIds.push(newBlockId);
13132
+ }
13133
+ messagesState.activeBlockIds.delete(block.blockId);
13134
+ const mappedId = messagesState.activeByAnchorMessageId.get(block.anchorMessageId);
13135
+ if (mappedId === block.blockId) {
13136
+ messagesState.activeByAnchorMessageId.delete(block.anchorMessageId);
13137
+ }
13105
13138
  }
13106
- for (const tier of [3, 2, 1]) {
13107
- const tierBlocks = blocks.filter((b) => (b.tier ?? 1) === tier).sort((a, b) => a.blockId - b.blockId);
13108
- if (tierBlocks.length === 0) continue;
13109
- out.push(`## ${TIER_NAMES[tier]}`);
13110
- out.push("");
13111
- for (const block of tierBlocks) {
13112
- const topic = block.topic || block.batchTopic || "(no topic)";
13113
- out.push(`### b${block.blockId} \u2014 ${topic}`);
13114
- out.push("");
13115
- if (includeMetadata) {
13116
- const mode = block.mode ?? "range";
13117
- const msgCount = block.effectiveMessageIds?.length ?? 0;
13118
- const created = new Date(block.createdAt).toISOString();
13119
- const age = block.survivedCount ?? 0;
13120
- out.push(`- **Tier**: T${tier} \xB7 **Mode**: ${mode}`);
13121
- out.push(`- **Messages**: ${msgCount} (effective)`);
13122
- out.push(
13123
- `- **Tokens**: ${formatTokens2(effectiveTokens(block))} \u2192 ${formatTokens2(block.summaryTokens || 0)} summary`
13124
- );
13125
- out.push(`- **Created**: ${created}`);
13126
- out.push(`- **Age**: survived ${age} transform${age === 1 ? "" : "s"}`);
13127
- out.push("");
13128
- }
13129
- const summary = (block.summary || "").trim() || "_(empty summary)_";
13130
- out.push(summary);
13131
- out.push("");
13132
- out.push("---");
13133
- out.push("");
13139
+ messagesState.blocksById.set(newBlockId, mergedBlock);
13140
+ messagesState.activeBlockIds.add(newBlockId);
13141
+ messagesState.activeByAnchorMessageId.set(mergedBlock.anchorMessageId, newBlockId);
13142
+ for (const messageId of effectiveMessageIds) {
13143
+ const entry = messagesState.byMessageId.get(messageId);
13144
+ if (!entry) continue;
13145
+ entry.activeBlockIds = entry.activeBlockIds.filter((id) => !sourceIds.includes(id));
13146
+ if (!entry.activeBlockIds.includes(newBlockId)) {
13147
+ entry.activeBlockIds.push(newBlockId);
13148
+ }
13149
+ if (!entry.allBlockIds.includes(newBlockId)) {
13150
+ entry.allBlockIds.push(newBlockId);
13134
13151
  }
13135
13152
  }
13136
- return out.join("\n");
13153
+ for (const id of sourceIds) {
13154
+ messagesState.markedForCleanup.delete(id);
13155
+ }
13156
+ const sourceTokens = sourceBlocks.reduce(
13157
+ (sum, block) => sum + (block.summaryTokens || Math.round(block.summary.length / 4)),
13158
+ 0
13159
+ );
13160
+ const savedTokens = Math.max(0, sourceTokens - newSummaryTokens);
13161
+ bumpPruneStructureVersion(messagesState);
13162
+ return { mergedCount: sourceBlocks.length, savedTokens };
13137
13163
  }
13138
- async function handleExportCommand(ctx, args) {
13139
- const { client, state, logger, sessionId } = ctx;
13140
- let options;
13141
- try {
13142
- options = parseExportArgs(args);
13143
- } catch (err) {
13144
- const msg = err?.message ?? String(err);
13145
- logger.warn("export: argument parse failed", { error: msg, args });
13146
- await sendExportNotice(client, sessionId, ctx, `[ACP Export] ${msg}`);
13147
- return;
13164
+ function runBatchCleanup(state, config, logger, messages) {
13165
+ const noop = {
13166
+ tier: 0,
13167
+ action: "none",
13168
+ mergedCount: 0,
13169
+ savedTokens: 0
13170
+ };
13171
+ const effective = resolveEffectiveContextLimit(state, config);
13172
+ if (!effective) {
13173
+ return noop;
13148
13174
  }
13149
- const tiers = options.tiers;
13150
- const allActive = collectActiveBlocks(state);
13151
- const blocks = filterByTier(allActive, tiers);
13152
- const generatedAt = /* @__PURE__ */ new Date();
13153
- const markdown = renderExportMarkdown({
13154
- sessionId,
13155
- generatedAt,
13156
- blocks,
13157
- tiers,
13158
- includeMetadata: options.includeMetadata
13159
- });
13160
- if (options.outputPath === "-") {
13161
- await sendExportNotice(client, sessionId, ctx, markdown);
13162
- return;
13175
+ const currentTokens = getCurrentTokenUsage(state, messages);
13176
+ if (currentTokens < effective.limit) {
13177
+ return noop;
13163
13178
  }
13164
- const cwd2 = ctx.workingDirectory || process.cwd();
13165
- const targetPath = options.outputPath !== "" ? isAbsolute2(options.outputPath) ? options.outputPath : resolve(cwd2, options.outputPath) : resolveDefaultOutputPath(sessionId, cwd2);
13166
- try {
13167
- const dir = dirname3(targetPath);
13168
- if (!existsSync7(dir)) {
13169
- await fs2.mkdir(dir, { recursive: true });
13170
- }
13171
- const flag = options.append ? "a" : "w";
13172
- if (options.append && existsSync7(targetPath)) {
13173
- await fs2.appendFile(targetPath, `
13174
-
13175
- ---
13176
-
13177
- ${markdown}`, "utf-8");
13178
- } else {
13179
- await fs2.writeFile(targetPath, markdown, { flag, encoding: "utf-8" });
13180
- }
13181
- } catch (err) {
13182
- const msg = err?.message ?? String(err);
13183
- logger.warn("export: file write failed", { path: targetPath, error: msg });
13184
- await sendExportNotice(
13185
- client,
13186
- sessionId,
13187
- ctx,
13188
- `[ACP Export] Failed to write \`${targetPath}\`: ${msg}`
13189
- );
13190
- return;
13179
+ const maxMergedLength = config.gc.maxOldGenSummaryLength;
13180
+ const oldGenBlocks = collectActiveOldGenBlocks(state, maxMergedLength);
13181
+ if (oldGenBlocks.length < 2) {
13182
+ return noop;
13191
13183
  }
13192
- logger.info("export: wrote markdown", {
13193
- path: targetPath,
13194
- blocks: blocks.length,
13195
- tiers: tiers.size ? [...tiers].sort().join(",") : "all"
13196
- });
13197
- const summary = formatExportSummary(targetPath, blocks, allActive, generatedAt);
13198
- await sendExportNotice(client, sessionId, ctx, summary);
13199
- }
13200
- function formatExportSummary(path, exported, allActive, generatedAt) {
13201
- const lines = [];
13202
- lines.push("[ACP Export]");
13203
- lines.push(`Wrote ${exported.length} block${exported.length === 1 ? "" : "s"} to:`);
13204
- lines.push(` ${path}`);
13205
- if (exported.length === 0) {
13206
- lines.push("");
13207
- lines.push(
13208
- `No matching blocks (of ${allActive.length} active). Try \`/acp export --tier all\`.`
13209
- );
13210
- } else {
13211
- lines.push("");
13212
- lines.push(`Generated ${generatedAt.toISOString()}.`);
13213
- lines.push(
13214
- "Review, edit, and commit as project notes \u2014 export is user-driven, never auto-injected."
13215
- );
13184
+ const ids = oldGenBlocks.map((b) => b.blockId);
13185
+ const result = mergeMarkedBlocks(state, ids, maxMergedLength);
13186
+ if (result.mergedCount === 0) {
13187
+ return noop;
13216
13188
  }
13217
- return lines.join("\n");
13218
- }
13219
- async function sendExportNotice(client, sessionId, ctx, text) {
13220
- await sendIgnoredMessage(client, sessionId, text, {}, ctx.logger);
13189
+ logger.info("Batch cleanup force fallback (100%): merged old-gen blocks", {
13190
+ mergedCount: result.mergedCount,
13191
+ savedTokens: result.savedTokens,
13192
+ currentTokens,
13193
+ contextLimit: effective.limit,
13194
+ contextLimitSource: effective.source
13195
+ });
13196
+ return {
13197
+ tier: 3,
13198
+ action: "merge",
13199
+ mergedCount: result.mergedCount,
13200
+ savedTokens: result.savedTokens
13201
+ };
13221
13202
  }
13222
13203
 
13223
- // src/messages/filter/registry.ts
13224
- var registry3 = /* @__PURE__ */ new Map();
13225
- function registerMessageFilter(filter) {
13226
- const existing = registry3.get(filter.name);
13227
- if (existing && existing.version !== filter.version) {
13228
- throw new Error(
13229
- `Message filter "${filter.name}" already registered with version ${existing.version}, cannot register version ${filter.version}. Use a different name or bump version.`
13230
- );
13204
+ // src/v2/hooks/messages.ts
13205
+ var INTERNAL_AGENT_NAMES = /* @__PURE__ */ new Set(["title", "summary", "compaction"]);
13206
+ function isInternalAgentRequest(messages) {
13207
+ const lastUserMessage = getLastUserMessage(messages);
13208
+ if (!lastUserMessage) {
13209
+ return false;
13231
13210
  }
13232
- registry3.set(filter.name, filter);
13233
- }
13234
- function getMessageFilter(name) {
13235
- return registry3.get(name);
13211
+ const agent = lastUserMessage.info.agent;
13212
+ return typeof agent === "string" && INTERNAL_AGENT_NAMES.has(agent);
13236
13213
  }
13237
- function listMessageFilters() {
13238
- return Array.from(registry3.values());
13239
- }
13240
-
13241
- // src/messages/filter/apply.ts
13242
- function applyMessageFilters(messages, config, logger, ctx) {
13243
- if (!config?.enabled) {
13244
- return { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
13245
- }
13246
- const allFilters = listMessageFilters().filter((f) => {
13247
- const fc = config.filters?.[f.name];
13248
- return fc?.enabled !== false;
13249
- });
13250
- if (allFilters.length === 0) {
13251
- return { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
13252
- }
13253
- const result = { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
13254
- const total = messages.length;
13255
- const warnedFilters = /* @__PURE__ */ new Set();
13256
- const buildCtx = (text, role, i) => ({
13257
- text,
13258
- role,
13259
- sessionId: ctx.sessionId,
13260
- isSubAgent: ctx.isSubAgent,
13261
- messageIndex: i,
13262
- totalMessages: total,
13263
- modelContextLimit: ctx.modelContextLimit
13264
- });
13265
- const applyDecision = (part, decision, filterName, i, originalText) => {
13266
- result.partsFiltered++;
13267
- if (decision.action === "drop") {
13268
- part.text = "";
13269
- result.partsDropped++;
13270
- if (decision.reason) {
13271
- logger.debug("Message filter dropped text", {
13272
- filter: filterName,
13273
- reason: decision.reason,
13274
- messageIndex: i,
13275
- originalLength: originalText.length
13214
+ function createChatMessageTransformHandler(client, registry4, logger, config, prompts, hostPermissions) {
13215
+ return async (input, output) => {
13216
+ const diagnostic = currentDiagnostic();
13217
+ const timeline = diagnostic?.timeline("transform", "filterMessages");
13218
+ const checkpoint = (nextStage) => timeline?.next(nextStage);
13219
+ try {
13220
+ const receivedMessages = Array.isArray(output.messages) ? output.messages.length : 0;
13221
+ const messages = filterMessagesInPlace(output.messages);
13222
+ if (messages.length !== receivedMessages) {
13223
+ logger.warn("Skipping messages with unexpected shape during chat transform", {
13224
+ received: receivedMessages,
13225
+ usable: messages.length
13276
13226
  });
13277
13227
  }
13278
- return "";
13279
- }
13280
- if (decision.action === "modify" && decision.text !== void 0) {
13281
- part.text = decision.text;
13282
- result.partsModified++;
13283
- if (decision.reason) {
13284
- logger.debug("Message filter modified text", {
13285
- filter: filterName,
13286
- reason: decision.reason,
13287
- messageIndex: i,
13288
- originalLength: originalText.length,
13289
- newLength: decision.text.length
13290
- });
13228
+ if (isInternalAgentRequest(messages)) {
13229
+ diagnostic?.skip("internal_agent");
13230
+ logger.debug("Skipping message transform for internal agent request");
13231
+ return;
13291
13232
  }
13292
- return decision.text;
13293
- }
13294
- return originalText;
13295
- };
13296
- const immediateFilters = allFilters.filter((f) => !f.keepLastOnly);
13297
- for (let i = 0; i < messages.length; i++) {
13298
- const msg = messages[i];
13299
- const role = msg.info.role ?? "unknown";
13300
- for (const part of msg.parts ?? []) {
13301
- const text = part.text;
13302
- if (typeof text !== "string" || text.length === 0) continue;
13303
- let current = text;
13304
- const filterCtx = buildCtx(current, role, i);
13305
- filterCtx.toolName = part.tool;
13306
- for (const filter of immediateFilters) {
13307
- let decision;
13308
- try {
13309
- decision = filter.filter(filterCtx);
13310
- } catch (err) {
13311
- if (!warnedFilters.has(filter.name)) {
13312
- warnedFilters.add(filter.name);
13313
- logger.warn("Message filter threw error", {
13314
- filter: filter.name,
13315
- error: err instanceof Error ? err.message : String(err),
13316
- messageIndex: i
13317
- });
13318
- }
13319
- continue;
13233
+ checkpoint("resolveSession");
13234
+ const lastUserMessage = getLastUserMessage(messages);
13235
+ let state;
13236
+ if (!lastUserMessage) {
13237
+ state = createSessionState();
13238
+ } else {
13239
+ state = await registry4.getOrCreate(
13240
+ client,
13241
+ lastUserMessage.info.sessionID,
13242
+ messages,
13243
+ config
13244
+ );
13245
+ checkpoint("resolveModel");
13246
+ const requestModel = lastUserMessage.info.model;
13247
+ let requestModelLimit = registry4.resolveModelLimit(
13248
+ requestModel?.providerID,
13249
+ requestModel?.modelID
13250
+ );
13251
+ if (requestModelLimit === void 0 && requestModel?.providerID && requestModel?.modelID) {
13252
+ requestModelLimit = await registry4.hydrateAndResolve(
13253
+ client,
13254
+ requestModel.providerID,
13255
+ requestModel.modelID
13256
+ );
13257
+ }
13258
+ const prevModelID = state.modelID;
13259
+ if (requestModelLimit !== void 0) {
13260
+ state.modelContextLimit = requestModelLimit;
13261
+ state.modelProviderID = requestModel?.providerID;
13262
+ state.modelID = requestModel?.modelID;
13263
+ } else if (
13264
+ // [FIX #312 fallback] Catalog miss: we cannot CORRECT the
13265
+ // limit, but we can tell when it belongs to a DIFFERENT model.
13266
+ // Invalidate instead of letting every percentage threshold
13267
+ // below run against the wrong window (#312's false positive).
13268
+ // States persisted before this identity pair existed carry no
13269
+ // identity and are treated as stale for the same reason.
13270
+ // Consumers already tolerate undefined — fresh sessions run
13271
+ // with it until the first system.transform sets the pair.
13272
+ requestModel?.providerID && requestModel?.modelID && state.modelContextLimit !== void 0 && (state.modelProviderID !== requestModel.providerID || state.modelID !== requestModel.modelID)
13273
+ ) {
13274
+ state.modelContextLimit = void 0;
13275
+ state.modelProviderID = requestModel.providerID;
13276
+ state.modelID = requestModel.modelID;
13277
+ }
13278
+ if (requestModel?.modelID && requestModel.modelID !== prevModelID) {
13279
+ logger.info("Model switched mid-session", {
13280
+ session: state.sessionId,
13281
+ from: prevModelID,
13282
+ to: requestModel.modelID,
13283
+ contextLimit: state.modelContextLimit
13284
+ });
13285
+ }
13286
+ checkpoint("updatePerTurnState");
13287
+ await updatePerTurnState(state, logger, messages);
13288
+ checkpoint("permissions");
13289
+ if (state.modelContextLimit === void 0 && !state.noContextLimitWarned && requestModel?.providerID && requestModel?.modelID && registry4.resolveModelLimit(requestModel.providerID, requestModel.modelID) === void 0) {
13290
+ state.noContextLimitWarned = true;
13291
+ logger.warn(
13292
+ '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.',
13293
+ {
13294
+ session: state.sessionId,
13295
+ model: `${requestModel.providerID}/${requestModel.modelID}`
13296
+ }
13297
+ );
13320
13298
  }
13321
- if (decision.action === "keep") continue;
13322
- current = applyDecision(part, decision, filter.name, i, current);
13323
- filterCtx.text = current;
13324
13299
  }
13325
- }
13326
- }
13327
- const keepLastFilters = allFilters.filter((f) => f.keepLastOnly);
13328
- for (const filter of keepLastFilters) {
13329
- const fcKeepLast = config.filters?.[filter.name]?.keepLast;
13330
- const keepCount = Math.max(1, fcKeepLast ?? filter.keepLast ?? 1);
13331
- let kept = 0;
13332
- for (let i = messages.length - 1; i >= 0; i--) {
13333
- const msg = messages[i];
13334
- const role = msg.info.role ?? "unknown";
13335
- const parts = msg.parts ?? [];
13336
- for (let p = parts.length - 1; p >= 0; p--) {
13337
- const part = parts[p];
13338
- const text = part.text;
13339
- if (typeof text !== "string" || text.length === 0) continue;
13340
- const filterCtx = buildCtx(text, role, i);
13341
- filterCtx.toolName = part.tool;
13342
- let decision;
13343
- try {
13344
- decision = filter.filter(filterCtx);
13345
- } catch {
13346
- continue;
13300
+ checkpoint("permissions");
13301
+ syncCompressPermissionState(state, config, hostPermissions, output.messages);
13302
+ if (diagnostic) {
13303
+ diagnostic.counts.blocks = state.prune.messages.blocksById.size;
13304
+ diagnostic.counts.activeBlocks = state.prune.messages.activeBlockIds.size;
13305
+ }
13306
+ if (state.isSubAgent && !config.allowSubAgents) {
13307
+ diagnostic?.skip("subagent_disabled");
13308
+ return;
13309
+ }
13310
+ checkpoint("stripHallucinations");
13311
+ stripHallucinations(output.messages);
13312
+ checkpoint("dropReasoning");
13313
+ const dropReasoningModel = lastUserMessage?.info?.model;
13314
+ const reasoningConfig = applyCompressOverrides(
13315
+ config,
13316
+ dropReasoningModel?.providerID ?? state.modelProviderID,
13317
+ dropReasoningModel?.modelID ?? state.modelID
13318
+ ).compress.reasoning;
13319
+ if (reasoningConfig?.drop !== false) {
13320
+ const droppedReasoning = dropCompressReasoning(
13321
+ output.messages,
13322
+ reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13323
+ );
13324
+ if (droppedReasoning > 0) {
13325
+ logger.debug("compress.reasoning: dropped oversized reasoning parts", {
13326
+ dropped: droppedReasoning,
13327
+ threshold: reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13328
+ });
13347
13329
  }
13348
- if (decision.action !== "drop" && decision.action !== "modify") continue;
13349
- if (kept < keepCount) {
13350
- kept++;
13351
- } else {
13352
- applyDecision(part, decision, filter.name, i, text);
13330
+ }
13331
+ checkpoint("messageFilters");
13332
+ ensureBuiltinFiltersRegistered();
13333
+ const effectiveLimit = resolveEffectiveContextLimit(state, config);
13334
+ applyMessageFilters(output.messages, config.messageFilters, logger, {
13335
+ sessionId: state.sessionId ?? "",
13336
+ isSubAgent: state.isSubAgent,
13337
+ modelContextLimit: effectiveLimit?.limit
13338
+ });
13339
+ checkpoint("cacheSystemPromptTokens");
13340
+ cacheSystemPromptTokens(state, output.messages);
13341
+ checkpoint("messageRefsAndImages");
13342
+ assignMessageRefs(state, output.messages);
13343
+ const imagesConfig = config.compress.images ?? DEFAULT_COMPRESS_IMAGES;
13344
+ if (imagesConfig.enabled) {
13345
+ const archivedImages = archiveSessionImages(
13346
+ state,
13347
+ output.messages,
13348
+ imagesConfig,
13349
+ logger
13350
+ );
13351
+ if (archivedImages > 0) {
13352
+ saveSessionState(state, logger).catch(() => {
13353
+ });
13353
13354
  }
13355
+ pruneImageArchive(state, imagesConfig, logger);
13354
13356
  }
13355
- }
13356
- }
13357
- if (result.partsFiltered > 0) {
13358
- logger.info("Message filters applied", {
13359
- filtersRun: allFilters.length,
13360
- partsFiltered: result.partsFiltered,
13361
- partsDropped: result.partsDropped,
13362
- partsModified: result.partsModified
13363
- });
13364
- }
13365
- return result;
13366
- }
13367
-
13368
- // src/messages/filter/builtin/omo-system-reminder.ts
13369
- var SYSTEM_REMINDER_OPEN = "<system-reminder>";
13370
- var OMO_MARKER = "<!-- OMO_INTERNAL_INITIATOR -->";
13371
- var PAIRED_BLOCK_RE = /<system-reminder>[\s\S]*?<\/system-reminder>\s*<!-- OMO_INTERNAL_INITIATOR -->/g;
13372
- var LONE_REMINDER_RE = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
13373
- var LONE_MARKER_RE = /<!-- OMO_INTERNAL_INITIATOR -->/g;
13374
- var OMO_SYSTEM_REMINDER_FILTER = {
13375
- name: "omo-system-reminder",
13376
- version: "1.3.0",
13377
- description: "Keep recent OMO <system-reminder> messages; for older ones, strip blocks but preserve user content",
13378
- keepLastOnly: true,
13379
- keepLast: 2,
13380
- filter(ctx) {
13381
- if (ctx.role !== "user") return { action: "keep" };
13382
- if (!ctx.text.includes(SYSTEM_REMINDER_OPEN) && !ctx.text.includes(OMO_MARKER)) {
13383
- return { action: "keep" };
13384
- }
13385
- let modified = ctx.text;
13386
- let removedBlocks = 0;
13387
- modified = modified.replace(PAIRED_BLOCK_RE, () => {
13388
- removedBlocks++;
13389
- return "";
13390
- });
13391
- modified = modified.replace(LONE_REMINDER_RE, () => {
13392
- removedBlocks++;
13393
- return "";
13394
- });
13395
- modified = modified.replace(LONE_MARKER_RE, "");
13396
- modified = modified.replace(/\n{3,}/g, "\n\n").trim();
13397
- if (modified.length === 0) {
13398
- return { action: "drop", reason: `Pure OMO system-reminder (${removedBlocks} block(s), no user content)` };
13399
- }
13400
- return {
13401
- action: "modify",
13402
- text: modified,
13403
- reason: `Stripped ${removedBlocks} OMO system-reminder block(s), preserved user content (${modified.length} chars)`
13404
- };
13405
- }
13406
- };
13407
-
13408
- // src/messages/filter/builtin/omo-todo-continuation.ts
13409
- var TODO_MARKER = "[SYSTEM DIRECTIVE";
13410
- var TODO_CONTINUATION = "TODO CONTINUATION";
13411
- var OMO_TODO_FILTER = {
13412
- name: "omo-todo-continuation",
13413
- version: "1.0.0",
13414
- description: "Keep only the latest OMO TODO CONTINUATION directive, drop earlier occurrences",
13415
- keepLastOnly: true,
13416
- filter(ctx) {
13417
- if (ctx.role !== "user") return { action: "keep" };
13418
- if (!ctx.text.includes(TODO_MARKER) || !ctx.text.includes(TODO_CONTINUATION)) {
13419
- return { action: "keep" };
13420
- }
13421
- return { action: "drop", reason: "TODO CONTINUATION directive" };
13422
- }
13423
- };
13424
-
13425
- // src/messages/filter/builtin/omo-context.ts
13426
- var OMO_MARKER2 = "<!-- OMO_INTERNAL_INITIATOR -->";
13427
- var OMO_CONTEXT_FILTER = {
13428
- name: "omo-context",
13429
- version: "1.0.0",
13430
- description: "Keep only the latest OMO [CONTEXT] injection, drop earlier occurrences",
13431
- keepLastOnly: true,
13432
- filter(ctx) {
13433
- if (ctx.role !== "user") return { action: "keep" };
13434
- if (!ctx.text.includes(OMO_MARKER2)) return { action: "keep" };
13435
- const stripped = ctx.text.trimStart();
13436
- if (!stripped.startsWith("[CONTEXT]") && !stripped.startsWith("CONTEXT:")) {
13437
- return { action: "keep" };
13438
- }
13439
- return { action: "drop", reason: "OMO context injection" };
13440
- }
13441
- };
13442
-
13443
- // src/messages/filter/builtin/omo-task-directive.ts
13444
- var OMO_MARKER3 = "<!-- OMO_INTERNAL_INITIATOR -->";
13445
- var OMO_TASK_FILTER = {
13446
- name: "omo-task-directive",
13447
- version: "1.0.0",
13448
- description: "Keep only the latest OMO TASK directive, drop earlier occurrences",
13449
- keepLastOnly: true,
13450
- filter(ctx) {
13451
- if (ctx.role !== "user") return { action: "keep" };
13452
- if (!ctx.text.includes(OMO_MARKER3)) return { action: "keep" };
13453
- const stripped = ctx.text.trimStart();
13454
- if (!stripped.startsWith("TASK:") && !stripped.startsWith("## TASK")) {
13455
- return { action: "keep" };
13456
- }
13457
- return { action: "drop", reason: "OMO task directive" };
13458
- }
13459
- };
13460
-
13461
- // src/messages/filter/builtin/omo-mode-injection.ts
13462
- var XML_MODE_TAGS = [
13463
- { open: "<hyperplan-ultrawork-mode>", close: "</hyperplan-ultrawork-mode>" },
13464
- { open: "<ultrawork-mode>", close: "</ultrawork-mode>" }
13465
- ];
13466
- var BRACKET_MODE_PATTERNS = ["[search-mode]", "[analyze-mode]", "[ultrawork-mode]"];
13467
- function stripLeadingModeInjections(text) {
13468
- let current = text;
13469
- let strippedAny = false;
13470
- for (let iter = 0; iter < 5; iter++) {
13471
- current = current.trimStart();
13472
- let matched = false;
13473
- for (const { open, close } of XML_MODE_TAGS) {
13474
- if (current.startsWith(open)) {
13475
- const closeIdx = current.indexOf(close);
13476
- if (closeIdx !== -1) {
13477
- current = current.slice(closeIdx + close.length);
13478
- } else {
13479
- current = current.slice(open.length);
13480
- }
13481
- matched = true;
13482
- break;
13357
+ checkpoint("syncCompressionBlocks");
13358
+ const activeBlockCountBefore = state.prune.messages.activeBlockIds.size;
13359
+ const compressionStateChanged = syncCompressionBlocks(state, logger, output.messages);
13360
+ if (compressionStateChanged || state.prune.messages.activeBlockIds.size !== activeBlockCountBefore) {
13361
+ saveSessionState(state, logger).catch(() => {
13362
+ });
13483
13363
  }
13484
- }
13485
- if (!matched) {
13486
- for (const pattern of BRACKET_MODE_PATTERNS) {
13487
- if (current.startsWith(pattern)) {
13488
- current = current.slice(pattern.length);
13489
- matched = true;
13490
- break;
13364
+ checkpoint("batchCleanup");
13365
+ buildToolIdList(state, output.messages);
13366
+ const batchResult = runBatchCleanup(state, config, logger, output.messages);
13367
+ if (batchResult.mergedCount > 0) {
13368
+ saveSessionState(state, logger).catch(() => {
13369
+ });
13370
+ }
13371
+ checkpoint("prePruneTokens");
13372
+ const prePruneTokens = getCurrentTokenUsage(state, output.messages);
13373
+ checkpoint("prune");
13374
+ const candidateMessages = config.compress.candidates === true ? output.messages.slice() : void 0;
13375
+ prune(state, logger, config, output.messages);
13376
+ checkpoint("compressNudges");
13377
+ hideConsumedCompressCalls(state, output.messages);
13378
+ assignMessageRefs(state, output.messages);
13379
+ const compressionPriorities = buildPriorityMap(config, state, output.messages);
13380
+ prompts.reload();
13381
+ injectCompressNudges(
13382
+ state,
13383
+ config,
13384
+ logger,
13385
+ output.messages,
13386
+ prompts.getRuntimePrompts(),
13387
+ compressionPriorities,
13388
+ config.debug ? (text) => {
13389
+ logger.debug(`[ACP Debug] Nudge injected:
13390
+ ${text}`);
13391
+ } : void 0,
13392
+ prePruneTokens,
13393
+ candidateMessages
13394
+ );
13395
+ checkpoint("emergencyTruncation");
13396
+ const emergencyTruncationEnabled = applyCompressOverrides(
13397
+ config,
13398
+ dropReasoningModel?.providerID ?? state.modelProviderID,
13399
+ dropReasoningModel?.modelID ?? state.modelID
13400
+ ).compress.emergencyTruncation;
13401
+ if (emergencyTruncationEnabled === true) {
13402
+ applyStickyTruncations(state, output.messages, logger);
13403
+ const toolOutputsBefore = snapshotToolOutputs(output.messages);
13404
+ truncateLargeToolOutputs(
13405
+ state,
13406
+ config,
13407
+ logger,
13408
+ output.messages.filter((message) => !isSyntheticMessage(message))
13409
+ );
13410
+ enforceContextBudget(state, config, logger, output.messages);
13411
+ const frozenCount = recordStickyTruncations(
13412
+ state,
13413
+ output.messages,
13414
+ toolOutputsBefore,
13415
+ logger
13416
+ );
13417
+ if (frozenCount > 0) {
13418
+ saveSessionState(state, logger).catch(() => {
13419
+ });
13491
13420
  }
13492
13421
  }
13493
- }
13494
- if (matched) {
13495
- strippedAny = true;
13496
- } else {
13497
- break;
13498
- }
13499
- }
13500
- return strippedAny ? current.trim() : null;
13501
- }
13502
- var OMO_MODE_FILTER = {
13503
- name: "omo-mode-injection",
13504
- version: "1.1.0",
13505
- description: "Strip OMO mode injection blocks (<ultrawork-mode>...</ultrawork-mode>, [search-mode], etc.) from user messages, preserving user content",
13506
- filter(ctx) {
13507
- if (ctx.role !== "user") return { action: "keep" };
13508
- const remaining = stripLeadingModeInjections(ctx.text);
13509
- if (remaining === null) return { action: "keep" };
13510
- if (remaining.length === 0) {
13511
- return { action: "drop", reason: "OMO mode injection (no user content after stripping)" };
13512
- }
13513
- return {
13514
- action: "modify",
13515
- text: remaining,
13516
- reason: "Stripped OMO mode injection block(s), preserved user content"
13517
- };
13518
- }
13519
- };
13520
-
13521
- // src/messages/filter/builtin/index.ts
13522
- var BUILTIN_FILTERS = [
13523
- OMO_SYSTEM_REMINDER_FILTER,
13524
- OMO_TODO_FILTER,
13525
- OMO_CONTEXT_FILTER,
13526
- OMO_TASK_FILTER,
13527
- OMO_MODE_FILTER
13528
- ];
13529
- function ensureBuiltinFiltersRegistered() {
13530
- for (const filter of BUILTIN_FILTERS) {
13531
- if (!getMessageFilter(filter.name)) {
13532
- registerMessageFilter(filter);
13533
- }
13534
- }
13535
- }
13536
-
13537
- // src/gc/merge.ts
13538
- function collectActiveOldGenBlocks(state, maxOldGenSummaryLength) {
13539
- const blocks = [];
13540
- const ids = Array.from(state.prune.messages.activeBlockIds).sort((a, b) => a - b);
13541
- for (const id of ids) {
13542
- const block = state.prune.messages.blocksById.get(id);
13543
- if (!block || !block.active) continue;
13544
- if (block.generation === "old" || block.generation === void 0 || block.summary.length > maxOldGenSummaryLength) {
13545
- blocks.push(block);
13546
- }
13547
- }
13548
- return blocks;
13549
- }
13550
- function extractSummaryBody(summary) {
13551
- let body = summary;
13552
- const headerPrefix = COMPRESSED_BLOCK_HEADER + "\n";
13553
- if (body.startsWith(headerPrefix)) {
13554
- body = body.slice(headerPrefix.length);
13555
- }
13556
- body = body.replace(/\n]*>b\d+<\/acp-message-id>$/, "");
13557
- return body.trim();
13558
- }
13559
- function truncateMergedSummary(merged, maxLength) {
13560
- if (merged.length <= maxLength) return merged;
13561
- const blocks = merged.split("\n---\n");
13562
- const headers = blocks.map((b) => b.split("\n")[0] ?? "").filter((h) => h.trim().length > 0);
13563
- const marker = "\n...\n[merged and truncated by batch cleanup]";
13564
- const budget = Math.max(0, maxLength - marker.length);
13565
- const headerJoin = headers.join("\n");
13566
- if (headerJoin.length <= budget) {
13567
- return headerJoin + marker;
13568
- }
13569
- return headerJoin.slice(0, budget) + marker;
13570
- }
13571
- function mergeMarkedBlocks(state, markedIds, maxMergedLength) {
13572
- const sortedIds = [...new Set(markedIds)].filter(
13573
- (id) => Number.isInteger(id) && id > 0
13574
- ).sort((a, b) => a - b);
13575
- const sourceBlocks = [];
13576
- for (const id of sortedIds) {
13577
- const block = state.prune.messages.blocksById.get(id);
13578
- if (!block || !block.active) continue;
13579
- if (!sourceBlocks.some((b) => b.blockId === id)) {
13580
- sourceBlocks.push(block);
13581
- }
13582
- }
13583
- if (sourceBlocks.length < 2) {
13584
- return { mergedCount: 0, savedTokens: 0 };
13585
- }
13586
- const messagesState = state.prune.messages;
13587
- const newBlockId = allocateBlockId(state);
13588
- const newRunId = allocateRunId(state);
13589
- const bodies = sourceBlocks.map((block) => extractSummaryBody(block.summary));
13590
- const mergedRaw = bodies.join("\n---\n");
13591
- const mergedBody = truncateMergedSummary(mergedRaw, maxMergedLength);
13592
- const newSummary = wrapCompressedSummary(newBlockId, mergedBody);
13593
- const newSummaryTokens = countTokens2(newSummary);
13594
- const oldest = sourceBlocks[0];
13595
- const newest = sourceBlocks[sourceBlocks.length - 1];
13596
- const effectiveMessageIds = /* @__PURE__ */ new Set();
13597
- const effectiveToolIds = /* @__PURE__ */ new Set();
13598
- for (const block of sourceBlocks) {
13599
- for (const id of block.effectiveMessageIds) effectiveMessageIds.add(id);
13600
- for (const id of block.effectiveToolIds) effectiveToolIds.add(id);
13601
- }
13602
- const sourceIds = sourceBlocks.map((b) => b.blockId);
13603
- const createdAt2 = Date.now();
13604
- const mergedBlock = {
13605
- blockId: newBlockId,
13606
- runId: newRunId,
13607
- active: true,
13608
- deactivatedByUser: false,
13609
- compressedTokens: 0,
13610
- summaryTokens: newSummaryTokens,
13611
- durationMs: 0,
13612
- mode: "range",
13613
- topic: "Batch merge cleanup",
13614
- batchTopic: "Batch merge cleanup",
13615
- startId: oldest.startId,
13616
- endId: newest.endId,
13617
- anchorMessageId: oldest.anchorMessageId,
13618
- compressMessageId: "",
13619
- compressCallId: void 0,
13620
- includedBlockIds: [...sourceIds],
13621
- consumedBlockIds: [...sourceIds],
13622
- parentBlockIds: [],
13623
- directMessageIds: [],
13624
- directToolIds: [],
13625
- effectiveMessageIds: [...effectiveMessageIds],
13626
- effectiveToolIds: [...effectiveToolIds],
13627
- createdAt: createdAt2,
13628
- summary: newSummary,
13629
- survivedCount: 0,
13630
- generation: "old"
13631
- };
13632
- const now = Date.now();
13633
- for (const block of sourceBlocks) {
13634
- block.active = false;
13635
- block.deactivatedAt = now;
13636
- block.deactivatedByBlockId = newBlockId;
13637
- if (!block.parentBlockIds.includes(newBlockId)) {
13638
- block.parentBlockIds.push(newBlockId);
13639
- }
13640
- messagesState.activeBlockIds.delete(block.blockId);
13641
- const mappedId = messagesState.activeByAnchorMessageId.get(block.anchorMessageId);
13642
- if (mappedId === block.blockId) {
13643
- messagesState.activeByAnchorMessageId.delete(block.anchorMessageId);
13644
- }
13645
- }
13646
- messagesState.blocksById.set(newBlockId, mergedBlock);
13647
- messagesState.activeBlockIds.add(newBlockId);
13648
- messagesState.activeByAnchorMessageId.set(mergedBlock.anchorMessageId, newBlockId);
13649
- for (const messageId of effectiveMessageIds) {
13650
- const entry = messagesState.byMessageId.get(messageId);
13651
- if (!entry) continue;
13652
- entry.activeBlockIds = entry.activeBlockIds.filter((id) => !sourceIds.includes(id));
13653
- if (!entry.activeBlockIds.includes(newBlockId)) {
13654
- entry.activeBlockIds.push(newBlockId);
13655
- }
13656
- if (!entry.allBlockIds.includes(newBlockId)) {
13657
- entry.allBlockIds.push(newBlockId);
13658
- }
13659
- }
13660
- for (const id of sourceIds) {
13661
- messagesState.markedForCleanup.delete(id);
13662
- }
13663
- const sourceTokens = sourceBlocks.reduce(
13664
- (sum, block) => sum + (block.summaryTokens || Math.round(block.summary.length / 4)),
13665
- 0
13666
- );
13667
- const savedTokens = Math.max(0, sourceTokens - newSummaryTokens);
13668
- bumpPruneStructureVersion(messagesState);
13669
- return { mergedCount: sourceBlocks.length, savedTokens };
13670
- }
13671
- function runBatchCleanup(state, config, logger, messages) {
13672
- const noop = {
13673
- tier: 0,
13674
- action: "none",
13675
- mergedCount: 0,
13676
- savedTokens: 0
13677
- };
13678
- const effective = resolveEffectiveContextLimit(state, config);
13679
- if (!effective) {
13680
- return noop;
13681
- }
13682
- const currentTokens = getCurrentTokenUsage(state, messages);
13683
- if (currentTokens < effective.limit) {
13684
- return noop;
13685
- }
13686
- const maxMergedLength = config.gc.maxOldGenSummaryLength;
13687
- const oldGenBlocks = collectActiveOldGenBlocks(state, maxMergedLength);
13688
- if (oldGenBlocks.length < 2) {
13689
- return noop;
13690
- }
13691
- const ids = oldGenBlocks.map((b) => b.blockId);
13692
- const result = mergeMarkedBlocks(state, ids, maxMergedLength);
13693
- if (result.mergedCount === 0) {
13694
- return noop;
13695
- }
13696
- logger.info("Batch cleanup force fallback (100%): merged old-gen blocks", {
13697
- mergedCount: result.mergedCount,
13698
- savedTokens: result.savedTokens,
13699
- currentTokens,
13700
- contextLimit: effective.limit,
13701
- contextLimitSource: effective.source
13702
- });
13703
- return {
13704
- tier: 3,
13705
- action: "merge",
13706
- mergedCount: result.mergedCount,
13707
- savedTokens: result.savedTokens
13708
- };
13709
- }
13710
-
13711
- // src/hooks.ts
13712
- var INTERNAL_AGENT_SIGNATURES = [
13713
- "You are a title generator",
13714
- "You are a helpful AI assistant tasked with summarizing conversations",
13715
- "You are an anchored context summarization assistant for coding sessions",
13716
- "Summarize what was done in this conversation"
13717
- ];
13718
- var INTERNAL_AGENT_NAMES = /* @__PURE__ */ new Set(["title", "summary", "compaction"]);
13719
- function isInternalAgentRequest(messages) {
13720
- const lastUserMessage = getLastUserMessage(messages);
13721
- if (!lastUserMessage) {
13722
- return false;
13723
- }
13724
- const agent = lastUserMessage.info.agent;
13725
- return typeof agent === "string" && INTERNAL_AGENT_NAMES.has(agent);
13726
- }
13727
- function createSystemPromptHandler(registry4, logger, config, prompts) {
13728
- return async (input, output) => {
13729
- registry4.recordModelLimit(
13730
- input.model?.providerID,
13731
- input.model?.id,
13732
- input.model?.limit?.context
13733
- );
13734
- const state = input.sessionID ? registry4.get(input.sessionID) : void 0;
13735
- if (!state || state.isSubAgent && !config.allowSubAgents) {
13736
- return;
13737
- }
13738
- const systemText = output.system.join("\n");
13739
- if (INTERNAL_AGENT_SIGNATURES.some((sig) => systemText.includes(sig))) {
13740
- logger.info("Skipping ACP system prompt injection for internal agent");
13741
- return;
13742
- }
13743
- if (input.model?.limit?.context) {
13744
- const limit = input.model.limit.context;
13745
- const providerID = input.model?.providerID;
13746
- const modelID = input.model?.id;
13747
- const changed = state.modelContextLimit !== limit || providerID !== void 0 && state.modelProviderID !== providerID || modelID !== void 0 && state.modelID !== modelID;
13748
- state.modelContextLimit = limit;
13749
- if (providerID !== void 0) {
13750
- state.modelProviderID = providerID;
13422
+ checkpoint("finalizeMessages");
13423
+ injectMessageIds(state, config, output.messages, compressionPriorities);
13424
+ hideFailedCompressCalls(output.messages);
13425
+ stripStaleMetadata(output.messages);
13426
+ dropEmptyMessages(output.messages);
13427
+ const smartPlanEnabled = applyCompressOverrides(
13428
+ config,
13429
+ state.modelProviderID,
13430
+ state.modelID
13431
+ ).compress.smartPlanRequired;
13432
+ if (state.sessionId && smartPlanEnabled === true) {
13433
+ recordVisibleMessages(state.sessionId, output.messages);
13751
13434
  }
13752
- if (modelID !== void 0) {
13753
- state.modelID = modelID;
13435
+ checkpoint("postTokens");
13436
+ const postTokens = getCurrentTokenUsage(state, output.messages);
13437
+ checkpoint("budgetGuard");
13438
+ if (postTokens !== void 0 && effectiveLimit) {
13439
+ const budget = effectiveLimit.limit - (state.systemPromptTokens ?? 0) - OUTPUT_RESERVE_TOKENS;
13440
+ if (postTokens > budget) {
13441
+ logger.error(
13442
+ "ACP hard guard: context exceeds model budget after in-flight reduction",
13443
+ {
13444
+ session: state.sessionId,
13445
+ postTokens,
13446
+ budget,
13447
+ contextLimit: effectiveLimit.limit,
13448
+ contextLimitSource: effectiveLimit.source,
13449
+ hint: "request will likely be rejected; run /compact or start a new session"
13450
+ }
13451
+ );
13452
+ }
13453
+ }
13454
+ logger.info("Chat transform complete", {
13455
+ session: state.sessionId,
13456
+ model: state.modelID,
13457
+ messages: output.messages.length,
13458
+ prePruneTokens,
13459
+ postTokens,
13460
+ contextLimit: effectiveLimit?.limit,
13461
+ contextLimitSource: effectiveLimit?.source,
13462
+ usagePct: postTokens !== void 0 && effectiveLimit ? `${(postTokens / effectiveLimit.limit * 100).toFixed(1)}%` : void 0,
13463
+ nudged: state.nudges.shouldInjectThisTurn
13464
+ });
13465
+ checkpoint("saveContext");
13466
+ if (diagnostic) {
13467
+ diagnostic.counts.blocks = state.prune.messages.blocksById.size;
13468
+ diagnostic.counts.activeBlocks = state.prune.messages.activeBlockIds.size;
13754
13469
  }
13755
- if (changed) {
13756
- saveSessionState(state, logger).catch(() => {
13757
- });
13470
+ if (state.sessionId) {
13471
+ await logger.saveContext(state.sessionId, output.messages);
13758
13472
  }
13759
- }
13760
- const effectivePermission = compressPermission(state, config);
13761
- if (effectivePermission === "deny") {
13762
- return;
13763
- }
13764
- prompts.reload();
13765
- const runtimePrompts = prompts.getRuntimePrompts();
13766
- const newPrompt = renderSystemPrompt(
13767
- runtimePrompts,
13768
- buildProtectedToolsExtension(config.compress.protectedTools),
13769
- state.isSubAgent && config.allowSubAgents
13770
- );
13771
- if (output.system.length > 0) {
13772
- output.system[output.system.length - 1] += "\n\n" + newPrompt;
13773
- } else {
13774
- output.system.push(newPrompt);
13473
+ } catch (error) {
13474
+ diagnostic?.fail("transform");
13475
+ throw error;
13476
+ } finally {
13477
+ timeline?.end();
13775
13478
  }
13776
13479
  };
13777
13480
  }
13778
- function createChatMessageTransformHandler(client, registry4, logger, config, prompts, hostPermissions) {
13779
- return async (input, output) => {
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
- });
13481
+
13482
+ // src/commands/context.ts
13483
+ function analyzeTokens(state, messages) {
13484
+ const breakdown = {
13485
+ system: 0,
13486
+ user: 0,
13487
+ assistant: 0,
13488
+ tools: 0,
13489
+ toolCount: 0,
13490
+ toolsInContextCount: 0,
13491
+ prunedTokens: state.stats.totalPruneTokens,
13492
+ prunedToolCount: 0,
13493
+ prunedMessageCount: 0,
13494
+ total: 0
13495
+ };
13496
+ let firstAssistant;
13497
+ for (const msg of messages) {
13498
+ if (msg.info.role === "assistant") {
13499
+ const assistantInfo = msg.info;
13500
+ if (assistantInfo.tokens?.input > 0 || assistantInfo.tokens?.cache?.read > 0 || assistantInfo.tokens?.cache?.write > 0) {
13501
+ firstAssistant = assistantInfo;
13502
+ break;
13791
13503
  }
13792
- if (isInternalAgentRequest(messages)) {
13793
- diagnostic?.skip("internal_agent");
13794
- logger.debug("Skipping message transform for internal agent request");
13795
- return;
13504
+ }
13505
+ }
13506
+ let lastAssistant;
13507
+ for (let i = messages.length - 1; i >= 0; i--) {
13508
+ const msg = messages[i];
13509
+ if (msg.info.role === "assistant") {
13510
+ const assistantInfo = msg.info;
13511
+ if (assistantInfo.tokens?.output > 0) {
13512
+ lastAssistant = assistantInfo;
13513
+ break;
13796
13514
  }
13797
- checkpoint("resolveSession");
13798
- const lastUserMessage = getLastUserMessage(messages);
13799
- let state;
13800
- if (!lastUserMessage) {
13801
- state = createSessionState();
13802
- } else {
13803
- state = await registry4.getOrCreate(
13804
- client,
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
13814
- );
13815
- if (requestModelLimit === void 0 && requestModel?.providerID && requestModel?.modelID) {
13816
- requestModelLimit = await registry4.hydrateAndResolve(
13817
- client,
13818
- requestModel.providerID,
13819
- requestModel.modelID
13820
- );
13515
+ }
13516
+ }
13517
+ const apiInput = lastAssistant?.tokens?.input || 0;
13518
+ const apiOutput = lastAssistant?.tokens?.output || 0;
13519
+ const apiReasoning = lastAssistant?.tokens?.reasoning || 0;
13520
+ const apiCacheRead = lastAssistant?.tokens?.cache?.read || 0;
13521
+ const apiCacheWrite = lastAssistant?.tokens?.cache?.write || 0;
13522
+ breakdown.total = apiInput + apiOutput + apiReasoning + apiCacheRead + apiCacheWrite;
13523
+ const userTextParts = [];
13524
+ const toolInputParts = [];
13525
+ const toolOutputParts = [];
13526
+ let firstUserText = "";
13527
+ let foundFirstUser = false;
13528
+ const allToolIds = /* @__PURE__ */ new Set();
13529
+ const activeToolIds = /* @__PURE__ */ new Set();
13530
+ const prunedToolIds = /* @__PURE__ */ new Set();
13531
+ const allMessageIds = /* @__PURE__ */ new Set();
13532
+ for (const msg of messages) {
13533
+ allMessageIds.add(msg.info.id);
13534
+ const parts = Array.isArray(msg.parts) ? msg.parts : [];
13535
+ const isCompacted = isMessageCompacted(state, msg);
13536
+ const pruneEntry = state.prune.messages.byMessageId.get(msg.info.id);
13537
+ const isMessagePruned = !!pruneEntry && pruneEntry.activeBlockIds.length > 0;
13538
+ const isIgnoredUser = isIgnoredUserMessage(msg);
13539
+ for (const part of parts) {
13540
+ if (part.type === "tool") {
13541
+ const toolPart = part;
13542
+ if (toolPart.callID) {
13543
+ allToolIds.add(toolPart.callID);
13544
+ if (!isCompacted) {
13545
+ activeToolIds.add(toolPart.callID);
13546
+ }
13547
+ if (isMessagePruned) {
13548
+ prunedToolIds.add(toolPart.callID);
13549
+ }
13821
13550
  }
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;
13551
+ if (!isCompacted) {
13552
+ if (toolPart.state?.input) {
13553
+ const inputStr = typeof toolPart.state.input === "string" ? toolPart.state.input : JSON.stringify(toolPart.state.input);
13554
+ toolInputParts.push(inputStr);
13555
+ }
13556
+ const outputStr = extractCompletedToolOutput(toolPart);
13557
+ if (outputStr !== void 0) {
13558
+ toolOutputParts.push(outputStr);
13559
+ }
13841
13560
  }
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
- });
13561
+ } else if (part.type === "text" && msg.info.role === "user" && !isCompacted && !isIgnoredUser) {
13562
+ const textPart = part;
13563
+ const text = textPart.text || "";
13564
+ userTextParts.push(text);
13565
+ if (!foundFirstUser) {
13566
+ firstUserText += text;
13849
13567
  }
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
- );
13568
+ }
13569
+ }
13570
+ if (msg.info.role === "user" && !isIgnoredUser && !foundFirstUser) {
13571
+ foundFirstUser = true;
13572
+ }
13573
+ }
13574
+ const toolsInContextCount = [...activeToolIds].filter((id) => !prunedToolIds.has(id)).length;
13575
+ let prunedMessageCount = 0;
13576
+ for (const [id, entry] of state.prune.messages.byMessageId) {
13577
+ if (allMessageIds.has(id) && entry.activeBlockIds.length > 0) {
13578
+ prunedMessageCount++;
13579
+ }
13580
+ }
13581
+ breakdown.toolCount = allToolIds.size;
13582
+ breakdown.toolsInContextCount = toolsInContextCount;
13583
+ breakdown.prunedToolCount = prunedToolIds.size;
13584
+ breakdown.prunedMessageCount = prunedMessageCount;
13585
+ const firstUserTokens = countTokens2(firstUserText);
13586
+ breakdown.user = countTokens2(userTextParts.join("\n"));
13587
+ const toolInputTokens = countTokens2(toolInputParts.join("\n"));
13588
+ const toolOutputTokens = countTokens2(toolOutputParts.join("\n"));
13589
+ if (firstAssistant) {
13590
+ const firstInput = (firstAssistant.tokens?.input || 0) + (firstAssistant.tokens?.cache?.read || 0) + (firstAssistant.tokens?.cache?.write || 0);
13591
+ breakdown.system = Math.max(0, firstInput - firstUserTokens);
13592
+ }
13593
+ breakdown.tools = toolInputTokens + toolOutputTokens;
13594
+ breakdown.assistant = Math.max(
13595
+ 0,
13596
+ breakdown.total - breakdown.system - breakdown.user - breakdown.tools
13597
+ );
13598
+ return breakdown;
13599
+ }
13600
+ function createBar(value, maxValue, width, char = "\u2588") {
13601
+ if (maxValue === 0) return "";
13602
+ const filled = Math.round(value / maxValue * width);
13603
+ const bar = char.repeat(Math.max(0, filled));
13604
+ return bar;
13605
+ }
13606
+ function formatContextMessage(breakdown) {
13607
+ const lines = [];
13608
+ const barWidth = 30;
13609
+ const toolsLabel = `Tools (${breakdown.toolsInContextCount})`;
13610
+ const categories = [
13611
+ { label: "System", value: breakdown.system, char: "\u2588" },
13612
+ { label: "User", value: breakdown.user, char: "\u2593" },
13613
+ { label: "Assistant", value: breakdown.assistant, char: "\u2592" },
13614
+ { label: toolsLabel, value: breakdown.tools, char: "\u2591" }
13615
+ ];
13616
+ const maxLabelLen = Math.max(...categories.map((c) => c.label.length));
13617
+ lines.push("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E");
13618
+ lines.push("\u2502 ACP Context Analysis \u2502");
13619
+ lines.push("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");
13620
+ lines.push("");
13621
+ lines.push("Session Context Breakdown:");
13622
+ lines.push("\u2500".repeat(60));
13623
+ lines.push("");
13624
+ for (const cat of categories) {
13625
+ const bar = createBar(cat.value, breakdown.total, barWidth, cat.char);
13626
+ const percentage = breakdown.total > 0 ? (cat.value / breakdown.total * 100).toFixed(1) : "0.0";
13627
+ const labelWithPct = `${cat.label.padEnd(maxLabelLen)} ${percentage.padStart(5)}% `;
13628
+ const valueStr = formatTokenCount(cat.value).padStart(13);
13629
+ lines.push(`${labelWithPct}\u2502${bar.padEnd(barWidth)}\u2502${valueStr}`);
13630
+ }
13631
+ lines.push("");
13632
+ lines.push("\u2500".repeat(60));
13633
+ lines.push("");
13634
+ lines.push("Summary:");
13635
+ if (breakdown.prunedTokens > 0) {
13636
+ const withoutPruning = breakdown.total + breakdown.prunedTokens;
13637
+ const pruned = [];
13638
+ if (breakdown.prunedToolCount > 0) pruned.push(`${breakdown.prunedToolCount} tools`);
13639
+ if (breakdown.prunedMessageCount > 0)
13640
+ pruned.push(`${breakdown.prunedMessageCount} messages`);
13641
+ lines.push(
13642
+ ` Pruned: ${pruned.join(", ")} (~${formatTokenCount(breakdown.prunedTokens)})`
13643
+ );
13644
+ lines.push(` Current context: ~${formatTokenCount(breakdown.total)}`);
13645
+ lines.push(` Without ACP: ~${formatTokenCount(withoutPruning)}`);
13646
+ } else {
13647
+ lines.push(` Current context: ~${formatTokenCount(breakdown.total)}`);
13648
+ }
13649
+ lines.push("");
13650
+ return lines.join("\n");
13651
+ }
13652
+ async function handleContextCommand(ctx) {
13653
+ const { client, state, logger, sessionId, messages } = ctx;
13654
+ const breakdown = analyzeTokens(state, messages);
13655
+ const message = formatContextMessage(breakdown);
13656
+ const params = getCurrentParams(state, messages, logger);
13657
+ await sendIgnoredMessage(client, sessionId, message, params, logger);
13658
+ }
13659
+
13660
+ // src/commands/stats.ts
13661
+ async function handleStatsCommand(ctx) {
13662
+ const report = buildStatusReport(
13663
+ { state: ctx.state, config: ctx.config },
13664
+ ctx.messages
13665
+ );
13666
+ const text = `[ACP Status]
13667
+ ${report}`;
13668
+ await sendIgnoredMessage(
13669
+ ctx.client,
13670
+ ctx.sessionId,
13671
+ text,
13672
+ {
13673
+ providerId: ctx.userInfo?.providerId,
13674
+ modelId: ctx.userInfo?.modelId,
13675
+ agent: ctx.userInfo?.agent,
13676
+ variant: ctx.userInfo?.variant
13677
+ },
13678
+ ctx.logger
13679
+ );
13680
+ }
13681
+
13682
+ // src/commands/export.ts
13683
+ import * as fs2 from "fs/promises";
13684
+ import { existsSync as existsSync7 } from "fs";
13685
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join7, resolve } from "path";
13686
+ var ALL_TIERS = [1, 2, 3];
13687
+ var TIER_NAMES = {
13688
+ 1: "Tier 1 \u2014 Capture",
13689
+ 2: "Tier 2 \u2014 Distilled",
13690
+ 3: "Tier 3 \u2014 Condensed"
13691
+ };
13692
+ function parseExportArgs(rawArgs) {
13693
+ const options = {
13694
+ outputPath: "",
13695
+ // "" sentinel => default path resolved later
13696
+ tiers: /* @__PURE__ */ new Set(),
13697
+ includeMetadata: true,
13698
+ append: false
13699
+ };
13700
+ const tokens = tokenize2(rawArgs);
13701
+ let i = 0;
13702
+ while (i < tokens.length) {
13703
+ const tok = tokens[i];
13704
+ const [flag, inlineValue] = splitFlag(tok);
13705
+ switch (flag) {
13706
+ case "--output":
13707
+ case "-o": {
13708
+ const value = inlineValue ?? tokens[i + 1];
13709
+ if (value === void 0) {
13710
+ throw new Error("--output requires a path (use `-` for stdout)");
13862
13711
  }
13712
+ options.outputPath = value;
13713
+ i += inlineValue !== void 0 ? 1 : 2;
13714
+ break;
13863
13715
  }
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;
13869
- }
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
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
- });
13716
+ case "--tier":
13717
+ case "-t": {
13718
+ const value = inlineValue ?? tokens[i + 1];
13719
+ if (value === void 0) {
13720
+ throw new Error("--tier requires a value (e.g. t2,t3 or all)");
13893
13721
  }
13722
+ options.tiers = parseTiers(value);
13723
+ i += inlineValue !== void 0 ? 1 : 2;
13724
+ break;
13894
13725
  }
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
- });
13726
+ case "--no-metadata":
13727
+ if (inlineValue !== void 0) {
13728
+ throw new Error("--no-metadata does not take a value");
13918
13729
  }
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(() => {
13926
- });
13927
- }
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) {
13934
- saveSessionState(state, logger).catch(() => {
13935
- });
13936
- }
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(
13948
- state,
13949
- config,
13950
- logger,
13951
- output.messages,
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
13960
- );
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))
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
- });
13730
+ options.includeMetadata = false;
13731
+ i += 1;
13732
+ break;
13733
+ case "--metadata":
13734
+ if (inlineValue !== void 0) {
13735
+ throw new Error("--metadata does not take a value");
13986
13736
  }
13987
- }
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
- );
13737
+ options.includeMetadata = true;
13738
+ i += 1;
13739
+ break;
13740
+ case "--append":
13741
+ if (inlineValue !== void 0) {
13742
+ throw new Error("--append does not take a value");
13743
+ }
13744
+ options.append = true;
13745
+ i += 1;
13746
+ break;
13747
+ case "--stdout":
13748
+ if (inlineValue !== void 0) {
13749
+ throw new Error("--stdout does not take a value");
14018
13750
  }
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();
13751
+ options.outputPath = "-";
13752
+ i += 1;
13753
+ break;
13754
+ default:
13755
+ throw new Error(
13756
+ `Unknown flag: ${tok}. Supported: --output, --tier, --no-metadata, --append, --stdout.`
13757
+ );
13758
+ }
13759
+ }
13760
+ return options;
13761
+ }
13762
+ function tokenize2(input) {
13763
+ const tokens = [];
13764
+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
13765
+ let m;
13766
+ while ((m = re.exec(input)) !== null) {
13767
+ tokens.push(m[1] ?? m[2] ?? m[3]);
13768
+ }
13769
+ return tokens;
13770
+ }
13771
+ function splitFlag(tok) {
13772
+ const eq = tok.indexOf("=");
13773
+ if (eq === -1) return [tok, void 0];
13774
+ return [tok.slice(0, eq), tok.slice(eq + 1)];
13775
+ }
13776
+ function parseTiers(raw) {
13777
+ const lower = raw.trim().toLowerCase();
13778
+ if (lower === "all") return new Set(ALL_TIERS);
13779
+ const parts = lower.split(",").map((p) => p.trim()).filter((p) => p.length > 0);
13780
+ const result = /* @__PURE__ */ new Set();
13781
+ for (const part of parts) {
13782
+ const digits = part.replace(/^t/i, "");
13783
+ const n = Number(digits);
13784
+ if (!Number.isInteger(n) || n < 1 || n > 3) {
13785
+ throw new Error(
13786
+ `Invalid tier "${part}". Expected t1, t2, t3, a combination (t2,t3), or "all".`
13787
+ );
13788
+ }
13789
+ result.add(n);
13790
+ }
13791
+ if (result.size === 0) {
13792
+ throw new Error(`Invalid tier "${raw}". Expected t1, t2, t3, or "all".`);
13793
+ }
13794
+ return result;
13795
+ }
13796
+ function resolveDefaultOutputPath(sessionId, cwd2) {
13797
+ const short = (sessionId || "session").slice(0, 8);
13798
+ return join7(cwd2, ".opencode", `acp-export-${short}.md`);
13799
+ }
13800
+ function formatTokens2(n) {
13801
+ if (!Number.isFinite(n) || n <= 0) return "0";
13802
+ return n >= 1e3 ? `${(n / 1e3).toFixed(1)}K` : String(n);
13803
+ }
13804
+ function effectiveTokens(block) {
13805
+ return block.effectiveCompressedTokens ?? block.compressedTokens ?? 0;
13806
+ }
13807
+ function collectActiveBlocks(state) {
13808
+ const msgState = state.prune.messages;
13809
+ const blocks = [];
13810
+ for (const id of msgState.activeBlockIds) {
13811
+ const block = msgState.blocksById.get(id);
13812
+ if (block && block.active) {
13813
+ blocks.push(block);
14044
13814
  }
13815
+ }
13816
+ return blocks;
13817
+ }
13818
+ function filterByTier(blocks, tiers) {
13819
+ if (tiers.size === 0) return blocks;
13820
+ return blocks.filter((b) => tiers.has(b.tier ?? 1));
13821
+ }
13822
+ function tokenSpans(blocks) {
13823
+ return {
13824
+ effective: blocks.reduce((s, b) => s + effectiveTokens(b), 0),
13825
+ summary: blocks.reduce((s, b) => s + (b.summaryTokens || 0), 0)
14045
13826
  };
14046
13827
  }
13828
+ function tierCounts(blocks) {
13829
+ const counts = {};
13830
+ for (const b of blocks) {
13831
+ const t = b.tier ?? 1;
13832
+ counts[t] = (counts[t] || 0) + 1;
13833
+ }
13834
+ return ALL_TIERS.filter((t) => counts[t]).map((t) => `T${t}: ${counts[t]}`).join(", ");
13835
+ }
13836
+ function renderExportMarkdown(params) {
13837
+ const { sessionId, generatedAt, blocks, tiers, includeMetadata } = params;
13838
+ const out = [];
13839
+ const tierFilterLabel = tiers.size === 0 ? "all" : ALL_TIERS.filter((t) => tiers.has(t)).map((t) => `T${t}`).join(", ");
13840
+ out.push("# ACP Session Export");
13841
+ out.push("");
13842
+ out.push(`- **Session**: \`${(sessionId || "unknown").slice(0, 16)}\``);
13843
+ out.push(`- **Generated**: ${generatedAt.toISOString()}`);
13844
+ out.push(`- **Blocks exported**: ${blocks.length}`);
13845
+ const breakdown = tierCounts(blocks);
13846
+ if (breakdown) {
13847
+ out.push(` - ${breakdown}`);
13848
+ }
13849
+ out.push(`- **Tiers**: ${tierFilterLabel}`);
13850
+ const span = tokenSpans(blocks);
13851
+ if (blocks.length > 0) {
13852
+ out.push(
13853
+ `- **Coverage**: ${formatTokens2(span.effective)} original \u2192 ${formatTokens2(span.summary)} summary`
13854
+ );
13855
+ }
13856
+ out.push("");
13857
+ out.push("---");
13858
+ out.push("");
13859
+ if (blocks.length === 0) {
13860
+ out.push("_No active compression blocks match the selected tiers._");
13861
+ out.push("");
13862
+ out.push(
13863
+ "Tip: run `/acp export --tier all` to include every active tier, or trigger a compression first."
13864
+ );
13865
+ return out.join("\n");
13866
+ }
13867
+ for (const tier of [3, 2, 1]) {
13868
+ const tierBlocks = blocks.filter((b) => (b.tier ?? 1) === tier).sort((a, b) => a.blockId - b.blockId);
13869
+ if (tierBlocks.length === 0) continue;
13870
+ out.push(`## ${TIER_NAMES[tier]}`);
13871
+ out.push("");
13872
+ for (const block of tierBlocks) {
13873
+ const topic = block.topic || block.batchTopic || "(no topic)";
13874
+ out.push(`### b${block.blockId} \u2014 ${topic}`);
13875
+ out.push("");
13876
+ if (includeMetadata) {
13877
+ const mode = block.mode ?? "range";
13878
+ const msgCount = block.effectiveMessageIds?.length ?? 0;
13879
+ const created = new Date(block.createdAt).toISOString();
13880
+ const age = block.survivedCount ?? 0;
13881
+ out.push(`- **Tier**: T${tier} \xB7 **Mode**: ${mode}`);
13882
+ out.push(`- **Messages**: ${msgCount} (effective)`);
13883
+ out.push(
13884
+ `- **Tokens**: ${formatTokens2(effectiveTokens(block))} \u2192 ${formatTokens2(block.summaryTokens || 0)} summary`
13885
+ );
13886
+ out.push(`- **Created**: ${created}`);
13887
+ out.push(`- **Age**: survived ${age} transform${age === 1 ? "" : "s"}`);
13888
+ out.push("");
13889
+ }
13890
+ const summary = (block.summary || "").trim() || "_(empty summary)_";
13891
+ out.push(summary);
13892
+ out.push("");
13893
+ out.push("---");
13894
+ out.push("");
13895
+ }
13896
+ }
13897
+ return out.join("\n");
13898
+ }
13899
+ async function handleExportCommand(ctx, args) {
13900
+ const { client, state, logger, sessionId } = ctx;
13901
+ let options;
13902
+ try {
13903
+ options = parseExportArgs(args);
13904
+ } catch (err) {
13905
+ const msg = err?.message ?? String(err);
13906
+ logger.warn("export: argument parse failed", { error: msg, args });
13907
+ await sendExportNotice(client, sessionId, ctx, `[ACP Export] ${msg}`);
13908
+ return;
13909
+ }
13910
+ const tiers = options.tiers;
13911
+ const allActive = collectActiveBlocks(state);
13912
+ const blocks = filterByTier(allActive, tiers);
13913
+ const generatedAt = /* @__PURE__ */ new Date();
13914
+ const markdown = renderExportMarkdown({
13915
+ sessionId,
13916
+ generatedAt,
13917
+ blocks,
13918
+ tiers,
13919
+ includeMetadata: options.includeMetadata
13920
+ });
13921
+ if (options.outputPath === "-") {
13922
+ await sendExportNotice(client, sessionId, ctx, markdown);
13923
+ return;
13924
+ }
13925
+ const cwd2 = ctx.workingDirectory || process.cwd();
13926
+ const targetPath = options.outputPath !== "" ? isAbsolute2(options.outputPath) ? options.outputPath : resolve(cwd2, options.outputPath) : resolveDefaultOutputPath(sessionId, cwd2);
13927
+ try {
13928
+ const dir = dirname3(targetPath);
13929
+ if (!existsSync7(dir)) {
13930
+ await fs2.mkdir(dir, { recursive: true });
13931
+ }
13932
+ const flag = options.append ? "a" : "w";
13933
+ if (options.append && existsSync7(targetPath)) {
13934
+ await fs2.appendFile(targetPath, `
13935
+
13936
+ ---
13937
+
13938
+ ${markdown}`, "utf-8");
13939
+ } else {
13940
+ await fs2.writeFile(targetPath, markdown, { flag, encoding: "utf-8" });
13941
+ }
13942
+ } catch (err) {
13943
+ const msg = err?.message ?? String(err);
13944
+ logger.warn("export: file write failed", { path: targetPath, error: msg });
13945
+ await sendExportNotice(
13946
+ client,
13947
+ sessionId,
13948
+ ctx,
13949
+ `[ACP Export] Failed to write \`${targetPath}\`: ${msg}`
13950
+ );
13951
+ return;
13952
+ }
13953
+ logger.info("export: wrote markdown", {
13954
+ path: targetPath,
13955
+ blocks: blocks.length,
13956
+ tiers: tiers.size ? [...tiers].sort().join(",") : "all"
13957
+ });
13958
+ const summary = formatExportSummary(targetPath, blocks, allActive, generatedAt);
13959
+ await sendExportNotice(client, sessionId, ctx, summary);
13960
+ }
13961
+ function formatExportSummary(path, exported, allActive, generatedAt) {
13962
+ const lines = [];
13963
+ lines.push("[ACP Export]");
13964
+ lines.push(`Wrote ${exported.length} block${exported.length === 1 ? "" : "s"} to:`);
13965
+ lines.push(` ${path}`);
13966
+ if (exported.length === 0) {
13967
+ lines.push("");
13968
+ lines.push(
13969
+ `No matching blocks (of ${allActive.length} active). Try \`/acp export --tier all\`.`
13970
+ );
13971
+ } else {
13972
+ lines.push("");
13973
+ lines.push(`Generated ${generatedAt.toISOString()}.`);
13974
+ lines.push(
13975
+ "Review, edit, and commit as project notes \u2014 export is user-driven, never auto-injected."
13976
+ );
13977
+ }
13978
+ return lines.join("\n");
13979
+ }
13980
+ async function sendExportNotice(client, sessionId, ctx, text) {
13981
+ await sendIgnoredMessage(client, sessionId, text, {}, ctx.logger);
13982
+ }
13983
+
13984
+ // src/v2/hooks/command.ts
14047
13985
  function buildHelpText() {
14048
13986
  return [
14049
13987
  "[ACP] Available commands:",
@@ -14093,6 +14031,8 @@ function createCommandExecuteHandler(client, registry4, logger, config, workingD
14093
14031
  }
14094
14032
  };
14095
14033
  }
14034
+
14035
+ // src/v2/hooks/event.ts
14096
14036
  function createEventHandler(registry4, logger) {
14097
14037
  return async (input) => {
14098
14038
  if (input.event?.type === "session.idle" || input.event?.type === "session.deleted") {