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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -11470,7 +11470,7 @@ import { writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
11470
11470
  import { join as join5 } from "path";
11471
11471
  import { existsSync as existsSync5 } from "fs";
11472
11472
  import { homedir as homedir3 } from "os";
11473
- var LOG_VERSION = true ? "2.0.0-alpha.2" : "dev";
11473
+ var LOG_VERSION = true ? "2.0.0-alpha.4" : "dev";
11474
11474
  var LEVEL_RANK = {
11475
11475
  debug: 10,
11476
11476
  info: 20,
@@ -11545,23 +11545,33 @@ var Logger = class {
11545
11545
  return "unknown";
11546
11546
  }
11547
11547
  }
11548
- async write(level, component, message, data) {
11548
+ async write(level, component, message, data, structured = false) {
11549
11549
  if (!this.shouldWrite(level.toLowerCase())) return;
11550
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
11550
11551
  try {
11551
11552
  await this.ensureLogDir();
11552
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
11553
- const dataStr = this.formatData(data);
11553
+ const dataStr = structured ? JSON.stringify(data) : this.formatData(data);
11554
11554
  const logLine = `${timestamp} ${level.padEnd(5)} ${component}: ${message}${dataStr ? " | " + dataStr : ""} | v=${LOG_VERSION}
11555
11555
  `;
11556
11556
  const dailyLogDir = join5(this.logDir, "daily");
11557
11557
  if (!existsSync5(dailyLogDir)) {
11558
11558
  await mkdir2(dailyLogDir, { recursive: true });
11559
11559
  }
11560
- const logFile = join5(dailyLogDir, `${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.log`);
11560
+ const logFile = join5(dailyLogDir, `${timestamp.split("T")[0]}.log`);
11561
11561
  await writeFile2(logFile, logLine, { flag: "a" });
11562
11562
  } catch (error) {
11563
11563
  }
11564
11564
  }
11565
+ /** One JSON payload on the existing daily sink; ordinary log formatting is unchanged. */
11566
+ diagnostic(event, data, level = "info") {
11567
+ return this.write(
11568
+ level.toUpperCase(),
11569
+ "diagnostics",
11570
+ event,
11571
+ { ...data, version: LOG_VERSION },
11572
+ true
11573
+ );
11574
+ }
11565
11575
  info(message, data) {
11566
11576
  if (!this.shouldWrite("info")) return;
11567
11577
  const component = this.getCallerFile(2);
@@ -11687,6 +11697,130 @@ var Logger = class {
11687
11697
  }
11688
11698
  };
11689
11699
 
11700
+ // src/diagnostics.ts
11701
+ import { AsyncLocalStorage } from "async_hooks";
11702
+ import { randomUUID } from "crypto";
11703
+ var requests = new AsyncLocalStorage();
11704
+ var instanceId = randomUUID();
11705
+ var sequence = 0;
11706
+ var milliseconds = (value) => Number(value.toFixed(3));
11707
+ var StageTimeline = class {
11708
+ constructor(stage, onStage) {
11709
+ this.stage = stage;
11710
+ this.onStage = onStage;
11711
+ onStage(stage);
11712
+ }
11713
+ stage;
11714
+ onStage;
11715
+ stageMs = {};
11716
+ checkpointAt = performance.now();
11717
+ ended = false;
11718
+ next(stage) {
11719
+ if (this.ended) return;
11720
+ const now = performance.now();
11721
+ this.stageMs[this.stage] = (this.stageMs[this.stage] ?? 0) + now - this.checkpointAt;
11722
+ this.checkpointAt = now;
11723
+ this.stage = stage;
11724
+ this.onStage(stage);
11725
+ }
11726
+ end() {
11727
+ if (this.ended) return;
11728
+ this.stageMs[this.stage] = (this.stageMs[this.stage] ?? 0) + performance.now() - this.checkpointAt;
11729
+ this.ended = true;
11730
+ }
11731
+ snapshot() {
11732
+ return Object.fromEntries(
11733
+ Object.entries(this.stageMs).map(([key, ms]) => [key, milliseconds(ms)])
11734
+ );
11735
+ }
11736
+ };
11737
+ var ContextDiagnostic = class {
11738
+ constructor(sessionId, logger) {
11739
+ this.sessionId = sessionId;
11740
+ this.logger = logger;
11741
+ }
11742
+ sessionId;
11743
+ logger;
11744
+ traceId = `${instanceId}-${++sequence}`;
11745
+ startedAt = performance.now();
11746
+ counts = {};
11747
+ lanes = /* @__PURE__ */ new Map();
11748
+ status = "ok";
11749
+ skipReason;
11750
+ failedStage;
11751
+ finished = false;
11752
+ timeline(lane, initialStage) {
11753
+ const timeline = new StageTimeline(initialStage, (stage) => {
11754
+ this.logger.debug("Context diagnostic stage", {
11755
+ sessionId: this.sessionId,
11756
+ traceId: this.traceId,
11757
+ lane,
11758
+ stage
11759
+ });
11760
+ });
11761
+ this.lanes.set(lane, timeline);
11762
+ return timeline;
11763
+ }
11764
+ skip(reason) {
11765
+ this.status = "skipped";
11766
+ this.skipReason = reason;
11767
+ }
11768
+ fail(lane) {
11769
+ this.status = "error";
11770
+ this.failedStage ??= `${lane}.${this.lanes.get(lane)?.stage ?? "unknown"}`;
11771
+ }
11772
+ get active() {
11773
+ return !this.finished;
11774
+ }
11775
+ finish() {
11776
+ if (this.finished) return;
11777
+ this.finished = true;
11778
+ for (const lane of this.lanes.values()) lane.end();
11779
+ try {
11780
+ void this.logger.diagnostic(
11781
+ "context",
11782
+ {
11783
+ schemaVersion: 1,
11784
+ instanceId,
11785
+ pid: process.pid,
11786
+ sessionId: this.sessionId,
11787
+ traceId: this.traceId,
11788
+ status: this.status,
11789
+ skipReason: this.skipReason,
11790
+ failedStage: this.failedStage,
11791
+ totalMs: milliseconds(performance.now() - this.startedAt),
11792
+ counts: this.counts,
11793
+ stageMs: Object.fromEntries(
11794
+ [...this.lanes].map(([name, lane]) => [name, lane.snapshot()])
11795
+ )
11796
+ },
11797
+ this.status === "error" ? "error" : "info"
11798
+ )?.catch(() => {
11799
+ });
11800
+ } catch {
11801
+ }
11802
+ }
11803
+ };
11804
+ function currentDiagnostic() {
11805
+ const request = requests.getStore();
11806
+ return request?.active ? request : void 0;
11807
+ }
11808
+ async function diagnoseContext(logger, sessionId, callback) {
11809
+ if (logger.level === "silent") return callback(void 0);
11810
+ const diagnostic = new ContextDiagnostic(sessionId, logger);
11811
+ return requests.run(diagnostic, async () => {
11812
+ logger.debug("Context diagnostic start", { sessionId, traceId: diagnostic.traceId });
11813
+ try {
11814
+ return await callback(diagnostic);
11815
+ } catch (error) {
11816
+ diagnostic.fail("context");
11817
+ throw error;
11818
+ } finally {
11819
+ diagnostic.finish();
11820
+ }
11821
+ });
11822
+ }
11823
+
11690
11824
  // src/prompts/store.ts
11691
11825
  import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync3, statSync as statSync3 } from "fs";
11692
11826
  import { join as join6, dirname as dirname2 } from "path";
@@ -12269,6 +12403,65 @@ function renderSystemPrompt(prompts, protectedToolsExtension, subagent) {
12269
12403
  return [prompts.system.trim(), ...extensions].filter(Boolean).join("\n\n").replace(/\n([ \t]*\n)+/g, "\n\n").trim();
12270
12404
  }
12271
12405
 
12406
+ // src/hooks/system.ts
12407
+ var INTERNAL_AGENT_SIGNATURES = [
12408
+ "You are a title generator",
12409
+ "You are a helpful AI assistant tasked with summarizing conversations",
12410
+ "You are an anchored context summarization assistant for coding sessions",
12411
+ "Summarize what was done in this conversation"
12412
+ ];
12413
+ function createSystemPromptHandler(registry4, logger, config, prompts) {
12414
+ return async (input, output) => {
12415
+ registry4.recordModelLimit(
12416
+ input.model?.providerID,
12417
+ input.model?.id,
12418
+ input.model?.limit?.context
12419
+ );
12420
+ const state = input.sessionID ? registry4.get(input.sessionID) : void 0;
12421
+ if (!state || state.isSubAgent && !config.allowSubAgents) {
12422
+ return;
12423
+ }
12424
+ const systemText = output.system.join("\n");
12425
+ if (INTERNAL_AGENT_SIGNATURES.some((sig) => systemText.includes(sig))) {
12426
+ logger.info("Skipping ACP system prompt injection for internal agent");
12427
+ return;
12428
+ }
12429
+ if (input.model?.limit?.context) {
12430
+ const limit = input.model.limit.context;
12431
+ const providerID = input.model?.providerID;
12432
+ const modelID = input.model?.id;
12433
+ const changed = state.modelContextLimit !== limit || providerID !== void 0 && state.modelProviderID !== providerID || modelID !== void 0 && state.modelID !== modelID;
12434
+ state.modelContextLimit = limit;
12435
+ if (providerID !== void 0) {
12436
+ state.modelProviderID = providerID;
12437
+ }
12438
+ if (modelID !== void 0) {
12439
+ state.modelID = modelID;
12440
+ }
12441
+ if (changed) {
12442
+ saveSessionState(state, logger).catch(() => {
12443
+ });
12444
+ }
12445
+ }
12446
+ const effectivePermission = compressPermission(state, config);
12447
+ if (effectivePermission === "deny") {
12448
+ return;
12449
+ }
12450
+ prompts.reload();
12451
+ const runtimePrompts = prompts.getRuntimePrompts();
12452
+ const newPrompt = renderSystemPrompt(
12453
+ runtimePrompts,
12454
+ buildProtectedToolsExtension(config.compress.protectedTools),
12455
+ state.isSubAgent && config.allowSubAgents
12456
+ );
12457
+ if (output.system.length > 0) {
12458
+ output.system[output.system.length - 1] += "\n\n" + newPrompt;
12459
+ } else {
12460
+ output.system.push(newPrompt);
12461
+ }
12462
+ };
12463
+ }
12464
+
12272
12465
  // src/messages/truncate-tools.ts
12273
12466
  var TRUNCATION_MARKER = "[truncated for context space";
12274
12467
  var MIN_OUTPUT_TOKENS = 1e3;
@@ -12584,1291 +12777,1277 @@ function enforceContextBudget(state, config, logger, messages) {
12584
12777
  };
12585
12778
  }
12586
12779
 
12587
- // src/commands/context.ts
12588
- function analyzeTokens(state, messages) {
12589
- const breakdown = {
12590
- system: 0,
12591
- user: 0,
12592
- assistant: 0,
12593
- tools: 0,
12594
- toolCount: 0,
12595
- toolsInContextCount: 0,
12596
- prunedTokens: state.stats.totalPruneTokens,
12597
- prunedToolCount: 0,
12598
- prunedMessageCount: 0,
12599
- total: 0
12780
+ // src/messages/filter/registry.ts
12781
+ var registry3 = /* @__PURE__ */ new Map();
12782
+ function registerMessageFilter(filter) {
12783
+ const existing = registry3.get(filter.name);
12784
+ if (existing && existing.version !== filter.version) {
12785
+ throw new Error(
12786
+ `Message filter "${filter.name}" already registered with version ${existing.version}, cannot register version ${filter.version}. Use a different name or bump version.`
12787
+ );
12788
+ }
12789
+ registry3.set(filter.name, filter);
12790
+ }
12791
+ function getMessageFilter(name) {
12792
+ return registry3.get(name);
12793
+ }
12794
+ function listMessageFilters() {
12795
+ return Array.from(registry3.values());
12796
+ }
12797
+
12798
+ // src/messages/filter/apply.ts
12799
+ function applyMessageFilters(messages, config, logger, ctx) {
12800
+ if (!config?.enabled) {
12801
+ return { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
12802
+ }
12803
+ const allFilters = listMessageFilters().filter((f) => {
12804
+ const fc = config.filters?.[f.name];
12805
+ return fc?.enabled !== false;
12806
+ });
12807
+ if (allFilters.length === 0) {
12808
+ return { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
12809
+ }
12810
+ const result = { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
12811
+ const total = messages.length;
12812
+ const warnedFilters = /* @__PURE__ */ new Set();
12813
+ const buildCtx = (text, role, i) => ({
12814
+ text,
12815
+ role,
12816
+ sessionId: ctx.sessionId,
12817
+ isSubAgent: ctx.isSubAgent,
12818
+ messageIndex: i,
12819
+ totalMessages: total,
12820
+ modelContextLimit: ctx.modelContextLimit
12821
+ });
12822
+ const applyDecision = (part, decision, filterName, i, originalText) => {
12823
+ result.partsFiltered++;
12824
+ if (decision.action === "drop") {
12825
+ part.text = "";
12826
+ result.partsDropped++;
12827
+ if (decision.reason) {
12828
+ logger.debug("Message filter dropped text", {
12829
+ filter: filterName,
12830
+ reason: decision.reason,
12831
+ messageIndex: i,
12832
+ originalLength: originalText.length
12833
+ });
12834
+ }
12835
+ return "";
12836
+ }
12837
+ if (decision.action === "modify" && decision.text !== void 0) {
12838
+ part.text = decision.text;
12839
+ result.partsModified++;
12840
+ if (decision.reason) {
12841
+ logger.debug("Message filter modified text", {
12842
+ filter: filterName,
12843
+ reason: decision.reason,
12844
+ messageIndex: i,
12845
+ originalLength: originalText.length,
12846
+ newLength: decision.text.length
12847
+ });
12848
+ }
12849
+ return decision.text;
12850
+ }
12851
+ return originalText;
12600
12852
  };
12601
- let firstAssistant;
12602
- for (const msg of messages) {
12603
- if (msg.info.role === "assistant") {
12604
- const assistantInfo = msg.info;
12605
- if (assistantInfo.tokens?.input > 0 || assistantInfo.tokens?.cache?.read > 0 || assistantInfo.tokens?.cache?.write > 0) {
12606
- firstAssistant = assistantInfo;
12607
- break;
12853
+ const immediateFilters = allFilters.filter((f) => !f.keepLastOnly);
12854
+ for (let i = 0; i < messages.length; i++) {
12855
+ const msg = messages[i];
12856
+ const role = msg.info.role ?? "unknown";
12857
+ for (const part of msg.parts ?? []) {
12858
+ const text = part.text;
12859
+ if (typeof text !== "string" || text.length === 0) continue;
12860
+ let current = text;
12861
+ const filterCtx = buildCtx(current, role, i);
12862
+ filterCtx.toolName = part.tool;
12863
+ for (const filter of immediateFilters) {
12864
+ let decision;
12865
+ try {
12866
+ decision = filter.filter(filterCtx);
12867
+ } catch (err) {
12868
+ if (!warnedFilters.has(filter.name)) {
12869
+ warnedFilters.add(filter.name);
12870
+ logger.warn("Message filter threw error", {
12871
+ filter: filter.name,
12872
+ error: err instanceof Error ? err.message : String(err),
12873
+ messageIndex: i
12874
+ });
12875
+ }
12876
+ continue;
12877
+ }
12878
+ if (decision.action === "keep") continue;
12879
+ current = applyDecision(part, decision, filter.name, i, current);
12880
+ filterCtx.text = current;
12608
12881
  }
12609
12882
  }
12610
12883
  }
12611
- let lastAssistant;
12612
- for (let i = messages.length - 1; i >= 0; i--) {
12613
- const msg = messages[i];
12614
- if (msg.info.role === "assistant") {
12615
- const assistantInfo = msg.info;
12616
- if (assistantInfo.tokens?.output > 0) {
12617
- lastAssistant = assistantInfo;
12618
- break;
12884
+ const keepLastFilters = allFilters.filter((f) => f.keepLastOnly);
12885
+ for (const filter of keepLastFilters) {
12886
+ const fcKeepLast = config.filters?.[filter.name]?.keepLast;
12887
+ const keepCount = Math.max(1, fcKeepLast ?? filter.keepLast ?? 1);
12888
+ let kept = 0;
12889
+ for (let i = messages.length - 1; i >= 0; i--) {
12890
+ const msg = messages[i];
12891
+ const role = msg.info.role ?? "unknown";
12892
+ const parts = msg.parts ?? [];
12893
+ for (let p = parts.length - 1; p >= 0; p--) {
12894
+ const part = parts[p];
12895
+ const text = part.text;
12896
+ if (typeof text !== "string" || text.length === 0) continue;
12897
+ const filterCtx = buildCtx(text, role, i);
12898
+ filterCtx.toolName = part.tool;
12899
+ let decision;
12900
+ try {
12901
+ decision = filter.filter(filterCtx);
12902
+ } catch {
12903
+ continue;
12904
+ }
12905
+ if (decision.action !== "drop" && decision.action !== "modify") continue;
12906
+ if (kept < keepCount) {
12907
+ kept++;
12908
+ } else {
12909
+ applyDecision(part, decision, filter.name, i, text);
12910
+ }
12619
12911
  }
12620
12912
  }
12621
12913
  }
12622
- const apiInput = lastAssistant?.tokens?.input || 0;
12623
- const apiOutput = lastAssistant?.tokens?.output || 0;
12624
- const apiReasoning = lastAssistant?.tokens?.reasoning || 0;
12625
- const apiCacheRead = lastAssistant?.tokens?.cache?.read || 0;
12626
- const apiCacheWrite = lastAssistant?.tokens?.cache?.write || 0;
12627
- breakdown.total = apiInput + apiOutput + apiReasoning + apiCacheRead + apiCacheWrite;
12628
- const userTextParts = [];
12629
- const toolInputParts = [];
12630
- const toolOutputParts = [];
12631
- let firstUserText = "";
12632
- let foundFirstUser = false;
12633
- const allToolIds = /* @__PURE__ */ new Set();
12634
- const activeToolIds = /* @__PURE__ */ new Set();
12635
- const prunedToolIds = /* @__PURE__ */ new Set();
12636
- const allMessageIds = /* @__PURE__ */ new Set();
12637
- for (const msg of messages) {
12638
- allMessageIds.add(msg.info.id);
12639
- const parts = Array.isArray(msg.parts) ? msg.parts : [];
12640
- const isCompacted = isMessageCompacted(state, msg);
12641
- const pruneEntry = state.prune.messages.byMessageId.get(msg.info.id);
12642
- const isMessagePruned = !!pruneEntry && pruneEntry.activeBlockIds.length > 0;
12643
- const isIgnoredUser = isIgnoredUserMessage(msg);
12644
- for (const part of parts) {
12645
- if (part.type === "tool") {
12646
- const toolPart = part;
12647
- if (toolPart.callID) {
12648
- allToolIds.add(toolPart.callID);
12649
- if (!isCompacted) {
12650
- activeToolIds.add(toolPart.callID);
12651
- }
12652
- if (isMessagePruned) {
12653
- prunedToolIds.add(toolPart.callID);
12654
- }
12655
- }
12656
- if (!isCompacted) {
12657
- if (toolPart.state?.input) {
12658
- const inputStr = typeof toolPart.state.input === "string" ? toolPart.state.input : JSON.stringify(toolPart.state.input);
12659
- toolInputParts.push(inputStr);
12660
- }
12661
- const outputStr = extractCompletedToolOutput(toolPart);
12662
- if (outputStr !== void 0) {
12663
- toolOutputParts.push(outputStr);
12664
- }
12665
- }
12666
- } else if (part.type === "text" && msg.info.role === "user" && !isCompacted && !isIgnoredUser) {
12667
- const textPart = part;
12668
- const text = textPart.text || "";
12669
- userTextParts.push(text);
12670
- if (!foundFirstUser) {
12671
- firstUserText += text;
12672
- }
12673
- }
12914
+ if (result.partsFiltered > 0) {
12915
+ logger.info("Message filters applied", {
12916
+ filtersRun: allFilters.length,
12917
+ partsFiltered: result.partsFiltered,
12918
+ partsDropped: result.partsDropped,
12919
+ partsModified: result.partsModified
12920
+ });
12921
+ }
12922
+ return result;
12923
+ }
12924
+
12925
+ // src/messages/filter/builtin/omo-system-reminder.ts
12926
+ var SYSTEM_REMINDER_OPEN = "<system-reminder>";
12927
+ var OMO_MARKER = "<!-- OMO_INTERNAL_INITIATOR -->";
12928
+ var PAIRED_BLOCK_RE = /<system-reminder>[\s\S]*?<\/system-reminder>\s*<!-- OMO_INTERNAL_INITIATOR -->/g;
12929
+ var LONE_REMINDER_RE = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
12930
+ var LONE_MARKER_RE = /<!-- OMO_INTERNAL_INITIATOR -->/g;
12931
+ var OMO_SYSTEM_REMINDER_FILTER = {
12932
+ name: "omo-system-reminder",
12933
+ version: "1.3.0",
12934
+ description: "Keep recent OMO <system-reminder> messages; for older ones, strip blocks but preserve user content",
12935
+ keepLastOnly: true,
12936
+ keepLast: 2,
12937
+ filter(ctx) {
12938
+ if (ctx.role !== "user") return { action: "keep" };
12939
+ if (!ctx.text.includes(SYSTEM_REMINDER_OPEN) && !ctx.text.includes(OMO_MARKER)) {
12940
+ return { action: "keep" };
12674
12941
  }
12675
- if (msg.info.role === "user" && !isIgnoredUser && !foundFirstUser) {
12676
- foundFirstUser = true;
12942
+ let modified = ctx.text;
12943
+ let removedBlocks = 0;
12944
+ modified = modified.replace(PAIRED_BLOCK_RE, () => {
12945
+ removedBlocks++;
12946
+ return "";
12947
+ });
12948
+ modified = modified.replace(LONE_REMINDER_RE, () => {
12949
+ removedBlocks++;
12950
+ return "";
12951
+ });
12952
+ modified = modified.replace(LONE_MARKER_RE, "");
12953
+ modified = modified.replace(/\n{3,}/g, "\n\n").trim();
12954
+ if (modified.length === 0) {
12955
+ return { action: "drop", reason: `Pure OMO system-reminder (${removedBlocks} block(s), no user content)` };
12677
12956
  }
12957
+ return {
12958
+ action: "modify",
12959
+ text: modified,
12960
+ reason: `Stripped ${removedBlocks} OMO system-reminder block(s), preserved user content (${modified.length} chars)`
12961
+ };
12678
12962
  }
12679
- const toolsInContextCount = [...activeToolIds].filter((id) => !prunedToolIds.has(id)).length;
12680
- let prunedMessageCount = 0;
12681
- for (const [id, entry] of state.prune.messages.byMessageId) {
12682
- if (allMessageIds.has(id) && entry.activeBlockIds.length > 0) {
12683
- prunedMessageCount++;
12963
+ };
12964
+
12965
+ // src/messages/filter/builtin/omo-todo-continuation.ts
12966
+ var TODO_MARKER = "[SYSTEM DIRECTIVE";
12967
+ var TODO_CONTINUATION = "TODO CONTINUATION";
12968
+ var OMO_TODO_FILTER = {
12969
+ name: "omo-todo-continuation",
12970
+ version: "1.0.0",
12971
+ description: "Keep only the latest OMO TODO CONTINUATION directive, drop earlier occurrences",
12972
+ keepLastOnly: true,
12973
+ filter(ctx) {
12974
+ if (ctx.role !== "user") return { action: "keep" };
12975
+ if (!ctx.text.includes(TODO_MARKER) || !ctx.text.includes(TODO_CONTINUATION)) {
12976
+ return { action: "keep" };
12684
12977
  }
12978
+ return { action: "drop", reason: "TODO CONTINUATION directive" };
12685
12979
  }
12686
- breakdown.toolCount = allToolIds.size;
12687
- breakdown.toolsInContextCount = toolsInContextCount;
12688
- breakdown.prunedToolCount = prunedToolIds.size;
12689
- breakdown.prunedMessageCount = prunedMessageCount;
12690
- const firstUserTokens = countTokens2(firstUserText);
12691
- breakdown.user = countTokens2(userTextParts.join("\n"));
12692
- const toolInputTokens = countTokens2(toolInputParts.join("\n"));
12693
- const toolOutputTokens = countTokens2(toolOutputParts.join("\n"));
12694
- if (firstAssistant) {
12695
- const firstInput = (firstAssistant.tokens?.input || 0) + (firstAssistant.tokens?.cache?.read || 0) + (firstAssistant.tokens?.cache?.write || 0);
12696
- breakdown.system = Math.max(0, firstInput - firstUserTokens);
12697
- }
12698
- breakdown.tools = toolInputTokens + toolOutputTokens;
12699
- breakdown.assistant = Math.max(
12700
- 0,
12701
- breakdown.total - breakdown.system - breakdown.user - breakdown.tools
12702
- );
12703
- return breakdown;
12704
- }
12705
- function createBar(value, maxValue, width, char = "\u2588") {
12706
- if (maxValue === 0) return "";
12707
- const filled = Math.round(value / maxValue * width);
12708
- const bar = char.repeat(Math.max(0, filled));
12709
- return bar;
12710
- }
12711
- function formatContextMessage(breakdown) {
12712
- const lines = [];
12713
- const barWidth = 30;
12714
- const toolsLabel = `Tools (${breakdown.toolsInContextCount})`;
12715
- const categories = [
12716
- { label: "System", value: breakdown.system, char: "\u2588" },
12717
- { label: "User", value: breakdown.user, char: "\u2593" },
12718
- { label: "Assistant", value: breakdown.assistant, char: "\u2592" },
12719
- { label: toolsLabel, value: breakdown.tools, char: "\u2591" }
12720
- ];
12721
- const maxLabelLen = Math.max(...categories.map((c) => c.label.length));
12722
- 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");
12723
- lines.push("\u2502 ACP Context Analysis \u2502");
12724
- 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");
12725
- lines.push("");
12726
- lines.push("Session Context Breakdown:");
12727
- lines.push("\u2500".repeat(60));
12728
- lines.push("");
12729
- for (const cat of categories) {
12730
- const bar = createBar(cat.value, breakdown.total, barWidth, cat.char);
12731
- const percentage = breakdown.total > 0 ? (cat.value / breakdown.total * 100).toFixed(1) : "0.0";
12732
- const labelWithPct = `${cat.label.padEnd(maxLabelLen)} ${percentage.padStart(5)}% `;
12733
- const valueStr = formatTokenCount(cat.value).padStart(13);
12734
- lines.push(`${labelWithPct}\u2502${bar.padEnd(barWidth)}\u2502${valueStr}`);
12735
- }
12736
- lines.push("");
12737
- lines.push("\u2500".repeat(60));
12738
- lines.push("");
12739
- lines.push("Summary:");
12740
- if (breakdown.prunedTokens > 0) {
12741
- const withoutPruning = breakdown.total + breakdown.prunedTokens;
12742
- const pruned = [];
12743
- if (breakdown.prunedToolCount > 0) pruned.push(`${breakdown.prunedToolCount} tools`);
12744
- if (breakdown.prunedMessageCount > 0)
12745
- pruned.push(`${breakdown.prunedMessageCount} messages`);
12746
- lines.push(
12747
- ` Pruned: ${pruned.join(", ")} (~${formatTokenCount(breakdown.prunedTokens)})`
12748
- );
12749
- lines.push(` Current context: ~${formatTokenCount(breakdown.total)}`);
12750
- lines.push(` Without ACP: ~${formatTokenCount(withoutPruning)}`);
12751
- } else {
12752
- lines.push(` Current context: ~${formatTokenCount(breakdown.total)}`);
12753
- }
12754
- lines.push("");
12755
- return lines.join("\n");
12756
- }
12757
- async function handleContextCommand(ctx) {
12758
- const { client, state, logger, sessionId, messages } = ctx;
12759
- const breakdown = analyzeTokens(state, messages);
12760
- const message = formatContextMessage(breakdown);
12761
- const params = getCurrentParams(state, messages, logger);
12762
- await sendIgnoredMessage(client, sessionId, message, params, logger);
12763
- }
12980
+ };
12764
12981
 
12765
- // src/commands/stats.ts
12766
- async function handleStatsCommand(ctx) {
12767
- const report = buildStatusReport(
12768
- { state: ctx.state, config: ctx.config },
12769
- ctx.messages
12770
- );
12771
- const text = `[ACP Status]
12772
- ${report}`;
12773
- await sendIgnoredMessage(
12774
- ctx.client,
12775
- ctx.sessionId,
12776
- text,
12777
- {
12778
- providerId: ctx.userInfo?.providerId,
12779
- modelId: ctx.userInfo?.modelId,
12780
- agent: ctx.userInfo?.agent,
12781
- variant: ctx.userInfo?.variant
12782
- },
12783
- ctx.logger
12784
- );
12785
- }
12982
+ // src/messages/filter/builtin/omo-context.ts
12983
+ var OMO_MARKER2 = "<!-- OMO_INTERNAL_INITIATOR -->";
12984
+ var OMO_CONTEXT_FILTER = {
12985
+ name: "omo-context",
12986
+ version: "1.0.0",
12987
+ description: "Keep only the latest OMO [CONTEXT] injection, drop earlier occurrences",
12988
+ keepLastOnly: true,
12989
+ filter(ctx) {
12990
+ if (ctx.role !== "user") return { action: "keep" };
12991
+ if (!ctx.text.includes(OMO_MARKER2)) return { action: "keep" };
12992
+ const stripped = ctx.text.trimStart();
12993
+ if (!stripped.startsWith("[CONTEXT]") && !stripped.startsWith("CONTEXT:")) {
12994
+ return { action: "keep" };
12995
+ }
12996
+ return { action: "drop", reason: "OMO context injection" };
12997
+ }
12998
+ };
12786
12999
 
12787
- // src/commands/export.ts
12788
- import * as fs2 from "fs/promises";
12789
- import { existsSync as existsSync7 } from "fs";
12790
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join7, resolve } from "path";
12791
- var ALL_TIERS = [1, 2, 3];
12792
- var TIER_NAMES = {
12793
- 1: "Tier 1 \u2014 Capture",
12794
- 2: "Tier 2 \u2014 Distilled",
12795
- 3: "Tier 3 \u2014 Condensed"
13000
+ // src/messages/filter/builtin/omo-task-directive.ts
13001
+ var OMO_MARKER3 = "<!-- OMO_INTERNAL_INITIATOR -->";
13002
+ var OMO_TASK_FILTER = {
13003
+ name: "omo-task-directive",
13004
+ version: "1.0.0",
13005
+ description: "Keep only the latest OMO TASK directive, drop earlier occurrences",
13006
+ keepLastOnly: true,
13007
+ filter(ctx) {
13008
+ if (ctx.role !== "user") return { action: "keep" };
13009
+ if (!ctx.text.includes(OMO_MARKER3)) return { action: "keep" };
13010
+ const stripped = ctx.text.trimStart();
13011
+ if (!stripped.startsWith("TASK:") && !stripped.startsWith("## TASK")) {
13012
+ return { action: "keep" };
13013
+ }
13014
+ return { action: "drop", reason: "OMO task directive" };
13015
+ }
12796
13016
  };
12797
- function parseExportArgs(rawArgs) {
12798
- const options = {
12799
- outputPath: "",
12800
- // "" sentinel => default path resolved later
12801
- tiers: /* @__PURE__ */ new Set(),
12802
- includeMetadata: true,
12803
- append: false
12804
- };
12805
- const tokens = tokenize2(rawArgs);
12806
- let i = 0;
12807
- while (i < tokens.length) {
12808
- const tok = tokens[i];
12809
- const [flag, inlineValue] = splitFlag(tok);
12810
- switch (flag) {
12811
- case "--output":
12812
- case "-o": {
12813
- const value = inlineValue ?? tokens[i + 1];
12814
- if (value === void 0) {
12815
- throw new Error("--output requires a path (use `-` for stdout)");
12816
- }
12817
- options.outputPath = value;
12818
- i += inlineValue !== void 0 ? 1 : 2;
12819
- break;
12820
- }
12821
- case "--tier":
12822
- case "-t": {
12823
- const value = inlineValue ?? tokens[i + 1];
12824
- if (value === void 0) {
12825
- throw new Error("--tier requires a value (e.g. t2,t3 or all)");
12826
- }
12827
- options.tiers = parseTiers(value);
12828
- i += inlineValue !== void 0 ? 1 : 2;
12829
- break;
12830
- }
12831
- case "--no-metadata":
12832
- if (inlineValue !== void 0) {
12833
- throw new Error("--no-metadata does not take a value");
12834
- }
12835
- options.includeMetadata = false;
12836
- i += 1;
12837
- break;
12838
- case "--metadata":
12839
- if (inlineValue !== void 0) {
12840
- throw new Error("--metadata does not take a value");
12841
- }
12842
- options.includeMetadata = true;
12843
- i += 1;
12844
- break;
12845
- case "--append":
12846
- if (inlineValue !== void 0) {
12847
- throw new Error("--append does not take a value");
12848
- }
12849
- options.append = true;
12850
- i += 1;
12851
- break;
12852
- case "--stdout":
12853
- if (inlineValue !== void 0) {
12854
- throw new Error("--stdout does not take a value");
13017
+
13018
+ // src/messages/filter/builtin/omo-mode-injection.ts
13019
+ var XML_MODE_TAGS = [
13020
+ { open: "<hyperplan-ultrawork-mode>", close: "</hyperplan-ultrawork-mode>" },
13021
+ { open: "<ultrawork-mode>", close: "</ultrawork-mode>" }
13022
+ ];
13023
+ var BRACKET_MODE_PATTERNS = ["[search-mode]", "[analyze-mode]", "[ultrawork-mode]"];
13024
+ function stripLeadingModeInjections(text) {
13025
+ let current = text;
13026
+ let strippedAny = false;
13027
+ for (let iter = 0; iter < 5; iter++) {
13028
+ current = current.trimStart();
13029
+ let matched = false;
13030
+ for (const { open, close } of XML_MODE_TAGS) {
13031
+ if (current.startsWith(open)) {
13032
+ const closeIdx = current.indexOf(close);
13033
+ if (closeIdx !== -1) {
13034
+ current = current.slice(closeIdx + close.length);
13035
+ } else {
13036
+ current = current.slice(open.length);
12855
13037
  }
12856
- options.outputPath = "-";
12857
- i += 1;
13038
+ matched = true;
12858
13039
  break;
12859
- default:
12860
- throw new Error(
12861
- `Unknown flag: ${tok}. Supported: --output, --tier, --no-metadata, --append, --stdout.`
12862
- );
13040
+ }
13041
+ }
13042
+ if (!matched) {
13043
+ for (const pattern of BRACKET_MODE_PATTERNS) {
13044
+ if (current.startsWith(pattern)) {
13045
+ current = current.slice(pattern.length);
13046
+ matched = true;
13047
+ break;
13048
+ }
13049
+ }
13050
+ }
13051
+ if (matched) {
13052
+ strippedAny = true;
13053
+ } else {
13054
+ break;
12863
13055
  }
12864
13056
  }
12865
- return options;
12866
- }
12867
- function tokenize2(input) {
12868
- const tokens = [];
12869
- const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
12870
- let m;
12871
- while ((m = re.exec(input)) !== null) {
12872
- tokens.push(m[1] ?? m[2] ?? m[3]);
12873
- }
12874
- return tokens;
12875
- }
12876
- function splitFlag(tok) {
12877
- const eq = tok.indexOf("=");
12878
- if (eq === -1) return [tok, void 0];
12879
- return [tok.slice(0, eq), tok.slice(eq + 1)];
13057
+ return strippedAny ? current.trim() : null;
12880
13058
  }
12881
- function parseTiers(raw) {
12882
- const lower = raw.trim().toLowerCase();
12883
- if (lower === "all") return new Set(ALL_TIERS);
12884
- const parts = lower.split(",").map((p) => p.trim()).filter((p) => p.length > 0);
12885
- const result = /* @__PURE__ */ new Set();
12886
- for (const part of parts) {
12887
- const digits = part.replace(/^t/i, "");
12888
- const n = Number(digits);
12889
- if (!Number.isInteger(n) || n < 1 || n > 3) {
12890
- throw new Error(
12891
- `Invalid tier "${part}". Expected t1, t2, t3, a combination (t2,t3), or "all".`
12892
- );
13059
+ var OMO_MODE_FILTER = {
13060
+ name: "omo-mode-injection",
13061
+ version: "1.1.0",
13062
+ description: "Strip OMO mode injection blocks (<ultrawork-mode>...</ultrawork-mode>, [search-mode], etc.) from user messages, preserving user content",
13063
+ filter(ctx) {
13064
+ if (ctx.role !== "user") return { action: "keep" };
13065
+ const remaining = stripLeadingModeInjections(ctx.text);
13066
+ if (remaining === null) return { action: "keep" };
13067
+ if (remaining.length === 0) {
13068
+ return { action: "drop", reason: "OMO mode injection (no user content after stripping)" };
12893
13069
  }
12894
- result.add(n);
13070
+ return {
13071
+ action: "modify",
13072
+ text: remaining,
13073
+ reason: "Stripped OMO mode injection block(s), preserved user content"
13074
+ };
12895
13075
  }
12896
- if (result.size === 0) {
12897
- throw new Error(`Invalid tier "${raw}". Expected t1, t2, t3, or "all".`);
13076
+ };
13077
+
13078
+ // src/messages/filter/builtin/index.ts
13079
+ var BUILTIN_FILTERS = [
13080
+ OMO_SYSTEM_REMINDER_FILTER,
13081
+ OMO_TODO_FILTER,
13082
+ OMO_CONTEXT_FILTER,
13083
+ OMO_TASK_FILTER,
13084
+ OMO_MODE_FILTER
13085
+ ];
13086
+ function ensureBuiltinFiltersRegistered() {
13087
+ for (const filter of BUILTIN_FILTERS) {
13088
+ if (!getMessageFilter(filter.name)) {
13089
+ registerMessageFilter(filter);
13090
+ }
12898
13091
  }
12899
- return result;
12900
- }
12901
- function resolveDefaultOutputPath(sessionId, cwd2) {
12902
- const short = (sessionId || "session").slice(0, 8);
12903
- return join7(cwd2, ".opencode", `acp-export-${short}.md`);
12904
- }
12905
- function formatTokens2(n) {
12906
- if (!Number.isFinite(n) || n <= 0) return "0";
12907
- return n >= 1e3 ? `${(n / 1e3).toFixed(1)}K` : String(n);
12908
- }
12909
- function effectiveTokens(block) {
12910
- return block.effectiveCompressedTokens ?? block.compressedTokens ?? 0;
12911
13092
  }
12912
- function collectActiveBlocks(state) {
12913
- const msgState = state.prune.messages;
13093
+
13094
+ // src/gc/merge.ts
13095
+ function collectActiveOldGenBlocks(state, maxOldGenSummaryLength) {
12914
13096
  const blocks = [];
12915
- for (const id of msgState.activeBlockIds) {
12916
- const block = msgState.blocksById.get(id);
12917
- if (block && block.active) {
13097
+ const ids = Array.from(state.prune.messages.activeBlockIds).sort((a, b) => a - b);
13098
+ for (const id of ids) {
13099
+ const block = state.prune.messages.blocksById.get(id);
13100
+ if (!block || !block.active) continue;
13101
+ if (block.generation === "old" || block.generation === void 0 || block.summary.length > maxOldGenSummaryLength) {
12918
13102
  blocks.push(block);
12919
13103
  }
12920
13104
  }
12921
13105
  return blocks;
12922
13106
  }
12923
- function filterByTier(blocks, tiers) {
12924
- if (tiers.size === 0) return blocks;
12925
- return blocks.filter((b) => tiers.has(b.tier ?? 1));
12926
- }
12927
- function tokenSpans(blocks) {
12928
- return {
12929
- effective: blocks.reduce((s, b) => s + effectiveTokens(b), 0),
12930
- summary: blocks.reduce((s, b) => s + (b.summaryTokens || 0), 0)
12931
- };
13107
+ function extractSummaryBody(summary) {
13108
+ let body = summary;
13109
+ const headerPrefix = COMPRESSED_BLOCK_HEADER + "\n";
13110
+ if (body.startsWith(headerPrefix)) {
13111
+ body = body.slice(headerPrefix.length);
13112
+ }
13113
+ body = body.replace(/\n]*>b\d+<\/acp-message-id>$/, "");
13114
+ return body.trim();
12932
13115
  }
12933
- function tierCounts(blocks) {
12934
- const counts = {};
12935
- for (const b of blocks) {
12936
- const t = b.tier ?? 1;
12937
- counts[t] = (counts[t] || 0) + 1;
13116
+ function truncateMergedSummary(merged, maxLength) {
13117
+ if (merged.length <= maxLength) return merged;
13118
+ const blocks = merged.split("\n---\n");
13119
+ const headers = blocks.map((b) => b.split("\n")[0] ?? "").filter((h) => h.trim().length > 0);
13120
+ const marker = "\n...\n[merged and truncated by batch cleanup]";
13121
+ const budget = Math.max(0, maxLength - marker.length);
13122
+ const headerJoin = headers.join("\n");
13123
+ if (headerJoin.length <= budget) {
13124
+ return headerJoin + marker;
12938
13125
  }
12939
- return ALL_TIERS.filter((t) => counts[t]).map((t) => `T${t}: ${counts[t]}`).join(", ");
13126
+ return headerJoin.slice(0, budget) + marker;
12940
13127
  }
12941
- function renderExportMarkdown(params) {
12942
- const { sessionId, generatedAt, blocks, tiers, includeMetadata } = params;
12943
- const out = [];
12944
- const tierFilterLabel = tiers.size === 0 ? "all" : ALL_TIERS.filter((t) => tiers.has(t)).map((t) => `T${t}`).join(", ");
12945
- out.push("# ACP Session Export");
12946
- out.push("");
12947
- out.push(`- **Session**: \`${(sessionId || "unknown").slice(0, 16)}\``);
12948
- out.push(`- **Generated**: ${generatedAt.toISOString()}`);
12949
- out.push(`- **Blocks exported**: ${blocks.length}`);
12950
- const breakdown = tierCounts(blocks);
12951
- if (breakdown) {
12952
- out.push(` - ${breakdown}`);
13128
+ function mergeMarkedBlocks(state, markedIds, maxMergedLength) {
13129
+ const sortedIds = [...new Set(markedIds)].filter(
13130
+ (id) => Number.isInteger(id) && id > 0
13131
+ ).sort((a, b) => a - b);
13132
+ const sourceBlocks = [];
13133
+ for (const id of sortedIds) {
13134
+ const block = state.prune.messages.blocksById.get(id);
13135
+ if (!block || !block.active) continue;
13136
+ if (!sourceBlocks.some((b) => b.blockId === id)) {
13137
+ sourceBlocks.push(block);
13138
+ }
12953
13139
  }
12954
- out.push(`- **Tiers**: ${tierFilterLabel}`);
12955
- const span = tokenSpans(blocks);
12956
- if (blocks.length > 0) {
12957
- out.push(
12958
- `- **Coverage**: ${formatTokens2(span.effective)} original \u2192 ${formatTokens2(span.summary)} summary`
12959
- );
13140
+ if (sourceBlocks.length < 2) {
13141
+ return { mergedCount: 0, savedTokens: 0 };
12960
13142
  }
12961
- out.push("");
12962
- out.push("---");
12963
- out.push("");
12964
- if (blocks.length === 0) {
12965
- out.push("_No active compression blocks match the selected tiers._");
12966
- out.push("");
12967
- out.push(
12968
- "Tip: run `/acp export --tier all` to include every active tier, or trigger a compression first."
12969
- );
12970
- return out.join("\n");
13143
+ const messagesState = state.prune.messages;
13144
+ const newBlockId = allocateBlockId(state);
13145
+ const newRunId = allocateRunId(state);
13146
+ const bodies = sourceBlocks.map((block) => extractSummaryBody(block.summary));
13147
+ const mergedRaw = bodies.join("\n---\n");
13148
+ const mergedBody = truncateMergedSummary(mergedRaw, maxMergedLength);
13149
+ const newSummary = wrapCompressedSummary(newBlockId, mergedBody);
13150
+ const newSummaryTokens = countTokens2(newSummary);
13151
+ const oldest = sourceBlocks[0];
13152
+ const newest = sourceBlocks[sourceBlocks.length - 1];
13153
+ const effectiveMessageIds = /* @__PURE__ */ new Set();
13154
+ const effectiveToolIds = /* @__PURE__ */ new Set();
13155
+ for (const block of sourceBlocks) {
13156
+ for (const id of block.effectiveMessageIds) effectiveMessageIds.add(id);
13157
+ for (const id of block.effectiveToolIds) effectiveToolIds.add(id);
12971
13158
  }
12972
- for (const tier of [3, 2, 1]) {
12973
- const tierBlocks = blocks.filter((b) => (b.tier ?? 1) === tier).sort((a, b) => a.blockId - b.blockId);
12974
- if (tierBlocks.length === 0) continue;
12975
- out.push(`## ${TIER_NAMES[tier]}`);
12976
- out.push("");
12977
- for (const block of tierBlocks) {
12978
- const topic = block.topic || block.batchTopic || "(no topic)";
12979
- out.push(`### b${block.blockId} \u2014 ${topic}`);
12980
- out.push("");
12981
- if (includeMetadata) {
12982
- const mode = block.mode ?? "range";
12983
- const msgCount = block.effectiveMessageIds?.length ?? 0;
12984
- const created = new Date(block.createdAt).toISOString();
12985
- const age = block.survivedCount ?? 0;
12986
- out.push(`- **Tier**: T${tier} \xB7 **Mode**: ${mode}`);
12987
- out.push(`- **Messages**: ${msgCount} (effective)`);
12988
- out.push(
12989
- `- **Tokens**: ${formatTokens2(effectiveTokens(block))} \u2192 ${formatTokens2(block.summaryTokens || 0)} summary`
12990
- );
12991
- out.push(`- **Created**: ${created}`);
12992
- out.push(`- **Age**: survived ${age} transform${age === 1 ? "" : "s"}`);
12993
- out.push("");
12994
- }
12995
- const summary = (block.summary || "").trim() || "_(empty summary)_";
12996
- out.push(summary);
12997
- out.push("");
12998
- out.push("---");
12999
- out.push("");
13159
+ const sourceIds = sourceBlocks.map((b) => b.blockId);
13160
+ const createdAt2 = Date.now();
13161
+ const mergedBlock = {
13162
+ blockId: newBlockId,
13163
+ runId: newRunId,
13164
+ active: true,
13165
+ deactivatedByUser: false,
13166
+ compressedTokens: 0,
13167
+ summaryTokens: newSummaryTokens,
13168
+ durationMs: 0,
13169
+ mode: "range",
13170
+ topic: "Batch merge cleanup",
13171
+ batchTopic: "Batch merge cleanup",
13172
+ startId: oldest.startId,
13173
+ endId: newest.endId,
13174
+ anchorMessageId: oldest.anchorMessageId,
13175
+ compressMessageId: "",
13176
+ compressCallId: void 0,
13177
+ includedBlockIds: [...sourceIds],
13178
+ consumedBlockIds: [...sourceIds],
13179
+ parentBlockIds: [],
13180
+ directMessageIds: [],
13181
+ directToolIds: [],
13182
+ effectiveMessageIds: [...effectiveMessageIds],
13183
+ effectiveToolIds: [...effectiveToolIds],
13184
+ createdAt: createdAt2,
13185
+ summary: newSummary,
13186
+ survivedCount: 0,
13187
+ generation: "old"
13188
+ };
13189
+ const now = Date.now();
13190
+ for (const block of sourceBlocks) {
13191
+ block.active = false;
13192
+ block.deactivatedAt = now;
13193
+ block.deactivatedByBlockId = newBlockId;
13194
+ if (!block.parentBlockIds.includes(newBlockId)) {
13195
+ block.parentBlockIds.push(newBlockId);
13196
+ }
13197
+ messagesState.activeBlockIds.delete(block.blockId);
13198
+ const mappedId = messagesState.activeByAnchorMessageId.get(block.anchorMessageId);
13199
+ if (mappedId === block.blockId) {
13200
+ messagesState.activeByAnchorMessageId.delete(block.anchorMessageId);
13000
13201
  }
13001
13202
  }
13002
- return out.join("\n");
13003
- }
13004
- async function handleExportCommand(ctx, args) {
13005
- const { client, state, logger, sessionId } = ctx;
13006
- let options;
13007
- try {
13008
- options = parseExportArgs(args);
13009
- } catch (err) {
13010
- const msg = err?.message ?? String(err);
13011
- logger.warn("export: argument parse failed", { error: msg, args });
13012
- await sendExportNotice(client, sessionId, ctx, `[ACP Export] ${msg}`);
13013
- return;
13014
- }
13015
- const tiers = options.tiers;
13016
- const allActive = collectActiveBlocks(state);
13017
- const blocks = filterByTier(allActive, tiers);
13018
- const generatedAt = /* @__PURE__ */ new Date();
13019
- const markdown = renderExportMarkdown({
13020
- sessionId,
13021
- generatedAt,
13022
- blocks,
13023
- tiers,
13024
- includeMetadata: options.includeMetadata
13025
- });
13026
- if (options.outputPath === "-") {
13027
- await sendExportNotice(client, sessionId, ctx, markdown);
13028
- return;
13029
- }
13030
- const cwd2 = ctx.workingDirectory || process.cwd();
13031
- const targetPath = options.outputPath !== "" ? isAbsolute2(options.outputPath) ? options.outputPath : resolve(cwd2, options.outputPath) : resolveDefaultOutputPath(sessionId, cwd2);
13032
- try {
13033
- const dir = dirname3(targetPath);
13034
- if (!existsSync7(dir)) {
13035
- await fs2.mkdir(dir, { recursive: true });
13203
+ messagesState.blocksById.set(newBlockId, mergedBlock);
13204
+ messagesState.activeBlockIds.add(newBlockId);
13205
+ messagesState.activeByAnchorMessageId.set(mergedBlock.anchorMessageId, newBlockId);
13206
+ for (const messageId of effectiveMessageIds) {
13207
+ const entry = messagesState.byMessageId.get(messageId);
13208
+ if (!entry) continue;
13209
+ entry.activeBlockIds = entry.activeBlockIds.filter((id) => !sourceIds.includes(id));
13210
+ if (!entry.activeBlockIds.includes(newBlockId)) {
13211
+ entry.activeBlockIds.push(newBlockId);
13036
13212
  }
13037
- const flag = options.append ? "a" : "w";
13038
- if (options.append && existsSync7(targetPath)) {
13039
- await fs2.appendFile(targetPath, `
13040
-
13041
- ---
13042
-
13043
- ${markdown}`, "utf-8");
13044
- } else {
13045
- await fs2.writeFile(targetPath, markdown, { flag, encoding: "utf-8" });
13213
+ if (!entry.allBlockIds.includes(newBlockId)) {
13214
+ entry.allBlockIds.push(newBlockId);
13046
13215
  }
13047
- } catch (err) {
13048
- const msg = err?.message ?? String(err);
13049
- logger.warn("export: file write failed", { path: targetPath, error: msg });
13050
- await sendExportNotice(
13051
- client,
13052
- sessionId,
13053
- ctx,
13054
- `[ACP Export] Failed to write \`${targetPath}\`: ${msg}`
13055
- );
13056
- return;
13057
13216
  }
13058
- logger.info("export: wrote markdown", {
13059
- path: targetPath,
13060
- blocks: blocks.length,
13061
- tiers: tiers.size ? [...tiers].sort().join(",") : "all"
13062
- });
13063
- const summary = formatExportSummary(targetPath, blocks, allActive, generatedAt);
13064
- await sendExportNotice(client, sessionId, ctx, summary);
13065
- }
13066
- function formatExportSummary(path, exported, allActive, generatedAt) {
13067
- const lines = [];
13068
- lines.push("[ACP Export]");
13069
- lines.push(`Wrote ${exported.length} block${exported.length === 1 ? "" : "s"} to:`);
13070
- lines.push(` ${path}`);
13071
- if (exported.length === 0) {
13072
- lines.push("");
13073
- lines.push(
13074
- `No matching blocks (of ${allActive.length} active). Try \`/acp export --tier all\`.`
13075
- );
13076
- } else {
13077
- lines.push("");
13078
- lines.push(`Generated ${generatedAt.toISOString()}.`);
13079
- lines.push(
13080
- "Review, edit, and commit as project notes \u2014 export is user-driven, never auto-injected."
13081
- );
13217
+ for (const id of sourceIds) {
13218
+ messagesState.markedForCleanup.delete(id);
13082
13219
  }
13083
- return lines.join("\n");
13084
- }
13085
- async function sendExportNotice(client, sessionId, ctx, text) {
13086
- await sendIgnoredMessage(client, sessionId, text, {}, ctx.logger);
13220
+ const sourceTokens = sourceBlocks.reduce(
13221
+ (sum, block) => sum + (block.summaryTokens || Math.round(block.summary.length / 4)),
13222
+ 0
13223
+ );
13224
+ const savedTokens = Math.max(0, sourceTokens - newSummaryTokens);
13225
+ bumpPruneStructureVersion(messagesState);
13226
+ return { mergedCount: sourceBlocks.length, savedTokens };
13087
13227
  }
13088
-
13089
- // src/messages/filter/registry.ts
13090
- var registry3 = /* @__PURE__ */ new Map();
13091
- function registerMessageFilter(filter) {
13092
- const existing = registry3.get(filter.name);
13093
- if (existing && existing.version !== filter.version) {
13094
- throw new Error(
13095
- `Message filter "${filter.name}" already registered with version ${existing.version}, cannot register version ${filter.version}. Use a different name or bump version.`
13096
- );
13228
+ function runBatchCleanup(state, config, logger, messages) {
13229
+ const noop = {
13230
+ tier: 0,
13231
+ action: "none",
13232
+ mergedCount: 0,
13233
+ savedTokens: 0
13234
+ };
13235
+ const effective = resolveEffectiveContextLimit(state, config);
13236
+ if (!effective) {
13237
+ return noop;
13097
13238
  }
13098
- registry3.set(filter.name, filter);
13099
- }
13100
- function getMessageFilter(name) {
13101
- return registry3.get(name);
13102
- }
13103
- function listMessageFilters() {
13104
- return Array.from(registry3.values());
13105
- }
13106
-
13107
- // src/messages/filter/apply.ts
13108
- function applyMessageFilters(messages, config, logger, ctx) {
13109
- if (!config?.enabled) {
13110
- return { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
13239
+ const currentTokens = getCurrentTokenUsage(state, messages);
13240
+ if (currentTokens < effective.limit) {
13241
+ return noop;
13111
13242
  }
13112
- const allFilters = listMessageFilters().filter((f) => {
13113
- const fc = config.filters?.[f.name];
13114
- return fc?.enabled !== false;
13115
- });
13116
- if (allFilters.length === 0) {
13117
- return { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
13243
+ const maxMergedLength = config.gc.maxOldGenSummaryLength;
13244
+ const oldGenBlocks = collectActiveOldGenBlocks(state, maxMergedLength);
13245
+ if (oldGenBlocks.length < 2) {
13246
+ return noop;
13118
13247
  }
13119
- const result = { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
13120
- const total = messages.length;
13121
- const warnedFilters = /* @__PURE__ */ new Set();
13122
- const buildCtx = (text, role, i) => ({
13123
- text,
13124
- role,
13125
- sessionId: ctx.sessionId,
13126
- isSubAgent: ctx.isSubAgent,
13127
- messageIndex: i,
13128
- totalMessages: total,
13129
- modelContextLimit: ctx.modelContextLimit
13248
+ const ids = oldGenBlocks.map((b) => b.blockId);
13249
+ const result = mergeMarkedBlocks(state, ids, maxMergedLength);
13250
+ if (result.mergedCount === 0) {
13251
+ return noop;
13252
+ }
13253
+ logger.info("Batch cleanup force fallback (100%): merged old-gen blocks", {
13254
+ mergedCount: result.mergedCount,
13255
+ savedTokens: result.savedTokens,
13256
+ currentTokens,
13257
+ contextLimit: effective.limit,
13258
+ contextLimitSource: effective.source
13130
13259
  });
13131
- const applyDecision = (part, decision, filterName, i, originalText) => {
13132
- result.partsFiltered++;
13133
- if (decision.action === "drop") {
13134
- part.text = "";
13135
- result.partsDropped++;
13136
- if (decision.reason) {
13137
- logger.debug("Message filter dropped text", {
13138
- filter: filterName,
13139
- reason: decision.reason,
13140
- messageIndex: i,
13141
- originalLength: originalText.length
13260
+ return {
13261
+ tier: 3,
13262
+ action: "merge",
13263
+ mergedCount: result.mergedCount,
13264
+ savedTokens: result.savedTokens
13265
+ };
13266
+ }
13267
+
13268
+ // src/hooks/messages.ts
13269
+ var INTERNAL_AGENT_NAMES = /* @__PURE__ */ new Set(["title", "summary", "compaction"]);
13270
+ function isInternalAgentRequest(messages) {
13271
+ const lastUserMessage = getLastUserMessage(messages);
13272
+ if (!lastUserMessage) {
13273
+ return false;
13274
+ }
13275
+ const agent = lastUserMessage.info.agent;
13276
+ return typeof agent === "string" && INTERNAL_AGENT_NAMES.has(agent);
13277
+ }
13278
+ function createChatMessageTransformHandler(client, registry4, logger, config, prompts, hostPermissions) {
13279
+ return async (input, output) => {
13280
+ const diagnostic = currentDiagnostic();
13281
+ const timeline = diagnostic?.timeline("transform", "filterMessages");
13282
+ const checkpoint = (nextStage) => timeline?.next(nextStage);
13283
+ try {
13284
+ const receivedMessages = Array.isArray(output.messages) ? output.messages.length : 0;
13285
+ const messages = filterMessagesInPlace(output.messages);
13286
+ if (messages.length !== receivedMessages) {
13287
+ logger.warn("Skipping messages with unexpected shape during chat transform", {
13288
+ received: receivedMessages,
13289
+ usable: messages.length
13142
13290
  });
13143
13291
  }
13144
- return "";
13145
- }
13146
- if (decision.action === "modify" && decision.text !== void 0) {
13147
- part.text = decision.text;
13148
- result.partsModified++;
13149
- if (decision.reason) {
13150
- logger.debug("Message filter modified text", {
13151
- filter: filterName,
13152
- reason: decision.reason,
13153
- messageIndex: i,
13154
- originalLength: originalText.length,
13155
- newLength: decision.text.length
13292
+ if (isInternalAgentRequest(messages)) {
13293
+ diagnostic?.skip("internal_agent");
13294
+ logger.debug("Skipping message transform for internal agent request");
13295
+ return;
13296
+ }
13297
+ checkpoint("resolveSession");
13298
+ const lastUserMessage = getLastUserMessage(messages);
13299
+ let state;
13300
+ if (!lastUserMessage) {
13301
+ state = createSessionState();
13302
+ } else {
13303
+ state = await registry4.getOrCreate(
13304
+ client,
13305
+ lastUserMessage.info.sessionID,
13306
+ messages,
13307
+ config
13308
+ );
13309
+ checkpoint("resolveModel");
13310
+ const requestModel = lastUserMessage.info.model;
13311
+ let requestModelLimit = registry4.resolveModelLimit(
13312
+ requestModel?.providerID,
13313
+ requestModel?.modelID
13314
+ );
13315
+ if (requestModelLimit === void 0 && requestModel?.providerID && requestModel?.modelID) {
13316
+ requestModelLimit = await registry4.hydrateAndResolve(
13317
+ client,
13318
+ requestModel.providerID,
13319
+ requestModel.modelID
13320
+ );
13321
+ }
13322
+ const prevModelID = state.modelID;
13323
+ if (requestModelLimit !== void 0) {
13324
+ state.modelContextLimit = requestModelLimit;
13325
+ state.modelProviderID = requestModel?.providerID;
13326
+ state.modelID = requestModel?.modelID;
13327
+ } else if (
13328
+ // [FIX #312 fallback] Catalog miss: we cannot CORRECT the
13329
+ // limit, but we can tell when it belongs to a DIFFERENT model.
13330
+ // Invalidate instead of letting every percentage threshold
13331
+ // below run against the wrong window (#312's false positive).
13332
+ // States persisted before this identity pair existed carry no
13333
+ // identity and are treated as stale for the same reason.
13334
+ // Consumers already tolerate undefined — fresh sessions run
13335
+ // with it until the first system.transform sets the pair.
13336
+ requestModel?.providerID && requestModel?.modelID && state.modelContextLimit !== void 0 && (state.modelProviderID !== requestModel.providerID || state.modelID !== requestModel.modelID)
13337
+ ) {
13338
+ state.modelContextLimit = void 0;
13339
+ state.modelProviderID = requestModel.providerID;
13340
+ state.modelID = requestModel.modelID;
13341
+ }
13342
+ if (requestModel?.modelID && requestModel.modelID !== prevModelID) {
13343
+ logger.info("Model switched mid-session", {
13344
+ session: state.sessionId,
13345
+ from: prevModelID,
13346
+ to: requestModel.modelID,
13347
+ contextLimit: state.modelContextLimit
13348
+ });
13349
+ }
13350
+ checkpoint("updatePerTurnState");
13351
+ await updatePerTurnState(state, logger, messages);
13352
+ checkpoint("permissions");
13353
+ if (state.modelContextLimit === void 0 && !state.noContextLimitWarned && requestModel?.providerID && requestModel?.modelID && registry4.resolveModelLimit(requestModel.providerID, requestModel.modelID) === void 0) {
13354
+ state.noContextLimitWarned = true;
13355
+ logger.warn(
13356
+ '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.',
13357
+ {
13358
+ session: state.sessionId,
13359
+ model: `${requestModel.providerID}/${requestModel.modelID}`
13360
+ }
13361
+ );
13362
+ }
13363
+ }
13364
+ checkpoint("permissions");
13365
+ syncCompressPermissionState(state, config, hostPermissions, output.messages);
13366
+ if (diagnostic) {
13367
+ diagnostic.counts.blocks = state.prune.messages.blocksById.size;
13368
+ diagnostic.counts.activeBlocks = state.prune.messages.activeBlockIds.size;
13369
+ }
13370
+ if (state.isSubAgent && !config.allowSubAgents) {
13371
+ diagnostic?.skip("subagent_disabled");
13372
+ return;
13373
+ }
13374
+ checkpoint("stripHallucinations");
13375
+ stripHallucinations(output.messages);
13376
+ checkpoint("dropReasoning");
13377
+ const dropReasoningModel = lastUserMessage?.info?.model;
13378
+ const reasoningConfig = applyCompressOverrides(
13379
+ config,
13380
+ dropReasoningModel?.providerID ?? state.modelProviderID,
13381
+ dropReasoningModel?.modelID ?? state.modelID
13382
+ ).compress.reasoning;
13383
+ if (reasoningConfig?.drop !== false) {
13384
+ const droppedReasoning = dropCompressReasoning(
13385
+ output.messages,
13386
+ reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13387
+ );
13388
+ if (droppedReasoning > 0) {
13389
+ logger.debug("compress.reasoning: dropped oversized reasoning parts", {
13390
+ dropped: droppedReasoning,
13391
+ threshold: reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13392
+ });
13393
+ }
13394
+ }
13395
+ checkpoint("messageFilters");
13396
+ ensureBuiltinFiltersRegistered();
13397
+ const effectiveLimit = resolveEffectiveContextLimit(state, config);
13398
+ applyMessageFilters(output.messages, config.messageFilters, logger, {
13399
+ sessionId: state.sessionId ?? "",
13400
+ isSubAgent: state.isSubAgent,
13401
+ modelContextLimit: effectiveLimit?.limit
13402
+ });
13403
+ checkpoint("cacheSystemPromptTokens");
13404
+ cacheSystemPromptTokens(state, output.messages);
13405
+ checkpoint("messageRefsAndImages");
13406
+ assignMessageRefs(state, output.messages);
13407
+ const imagesConfig = config.compress.images ?? DEFAULT_COMPRESS_IMAGES;
13408
+ if (imagesConfig.enabled) {
13409
+ const archivedImages = archiveSessionImages(
13410
+ state,
13411
+ output.messages,
13412
+ imagesConfig,
13413
+ logger
13414
+ );
13415
+ if (archivedImages > 0) {
13416
+ saveSessionState(state, logger).catch(() => {
13417
+ });
13418
+ }
13419
+ pruneImageArchive(state, imagesConfig, logger);
13420
+ }
13421
+ checkpoint("syncCompressionBlocks");
13422
+ const activeBlockCountBefore = state.prune.messages.activeBlockIds.size;
13423
+ const compressionStateChanged = syncCompressionBlocks(state, logger, output.messages);
13424
+ if (compressionStateChanged || state.prune.messages.activeBlockIds.size !== activeBlockCountBefore) {
13425
+ saveSessionState(state, logger).catch(() => {
13426
+ });
13427
+ }
13428
+ checkpoint("syncToolCache");
13429
+ syncToolCache(state, config, logger, output.messages);
13430
+ checkpoint("batchCleanup");
13431
+ buildToolIdList(state, output.messages);
13432
+ const batchResult = runBatchCleanup(state, config, logger, output.messages);
13433
+ if (batchResult.mergedCount > 0) {
13434
+ saveSessionState(state, logger).catch(() => {
13156
13435
  });
13157
13436
  }
13158
- return decision.text;
13159
- }
13160
- return originalText;
13161
- };
13162
- const immediateFilters = allFilters.filter((f) => !f.keepLastOnly);
13163
- for (let i = 0; i < messages.length; i++) {
13164
- const msg = messages[i];
13165
- const role = msg.info.role ?? "unknown";
13166
- for (const part of msg.parts ?? []) {
13167
- const text = part.text;
13168
- if (typeof text !== "string" || text.length === 0) continue;
13169
- let current = text;
13170
- const filterCtx = buildCtx(current, role, i);
13171
- filterCtx.toolName = part.tool;
13172
- for (const filter of immediateFilters) {
13173
- let decision;
13174
- try {
13175
- decision = filter.filter(filterCtx);
13176
- } catch (err) {
13177
- if (!warnedFilters.has(filter.name)) {
13178
- warnedFilters.add(filter.name);
13179
- logger.warn("Message filter threw error", {
13180
- filter: filter.name,
13181
- error: err instanceof Error ? err.message : String(err),
13182
- messageIndex: i
13183
- });
13184
- }
13185
- continue;
13437
+ checkpoint("prePruneTokens");
13438
+ const prePruneTokens = getCurrentTokenUsage(state, output.messages);
13439
+ checkpoint("prune");
13440
+ const candidateMessages = config.compress.candidates === true ? output.messages.slice() : void 0;
13441
+ prune(state, logger, config, output.messages);
13442
+ checkpoint("compressNudges");
13443
+ hideConsumedCompressCalls(state, output.messages);
13444
+ assignMessageRefs(state, output.messages);
13445
+ const compressionPriorities = buildPriorityMap(config, state, output.messages);
13446
+ prompts.reload();
13447
+ injectCompressNudges(
13448
+ state,
13449
+ config,
13450
+ logger,
13451
+ output.messages,
13452
+ prompts.getRuntimePrompts(),
13453
+ compressionPriorities,
13454
+ config.debug ? (text) => {
13455
+ logger.debug(`[ACP Debug] Nudge injected:
13456
+ ${text}`);
13457
+ } : void 0,
13458
+ prePruneTokens,
13459
+ candidateMessages
13460
+ );
13461
+ checkpoint("emergencyTruncation");
13462
+ const emergencyTruncationEnabled = applyCompressOverrides(
13463
+ config,
13464
+ dropReasoningModel?.providerID ?? state.modelProviderID,
13465
+ dropReasoningModel?.modelID ?? state.modelID
13466
+ ).compress.emergencyTruncation;
13467
+ if (emergencyTruncationEnabled === true) {
13468
+ applyStickyTruncations(state, output.messages, logger);
13469
+ const toolOutputsBefore = snapshotToolOutputs(output.messages);
13470
+ truncateLargeToolOutputs(
13471
+ state,
13472
+ config,
13473
+ logger,
13474
+ output.messages.filter((message) => !isSyntheticMessage(message))
13475
+ );
13476
+ enforceContextBudget(state, config, logger, output.messages);
13477
+ const frozenCount = recordStickyTruncations(
13478
+ state,
13479
+ output.messages,
13480
+ toolOutputsBefore,
13481
+ logger
13482
+ );
13483
+ if (frozenCount > 0) {
13484
+ saveSessionState(state, logger).catch(() => {
13485
+ });
13186
13486
  }
13187
- if (decision.action === "keep") continue;
13188
- current = applyDecision(part, decision, filter.name, i, current);
13189
- filterCtx.text = current;
13190
13487
  }
13191
- }
13192
- }
13193
- const keepLastFilters = allFilters.filter((f) => f.keepLastOnly);
13194
- for (const filter of keepLastFilters) {
13195
- const fcKeepLast = config.filters?.[filter.name]?.keepLast;
13196
- const keepCount = Math.max(1, fcKeepLast ?? filter.keepLast ?? 1);
13197
- let kept = 0;
13198
- for (let i = messages.length - 1; i >= 0; i--) {
13199
- const msg = messages[i];
13200
- const role = msg.info.role ?? "unknown";
13201
- const parts = msg.parts ?? [];
13202
- for (let p = parts.length - 1; p >= 0; p--) {
13203
- const part = parts[p];
13204
- const text = part.text;
13205
- if (typeof text !== "string" || text.length === 0) continue;
13206
- const filterCtx = buildCtx(text, role, i);
13207
- filterCtx.toolName = part.tool;
13208
- let decision;
13209
- try {
13210
- decision = filter.filter(filterCtx);
13211
- } catch {
13212
- continue;
13213
- }
13214
- if (decision.action !== "drop" && decision.action !== "modify") continue;
13215
- if (kept < keepCount) {
13216
- kept++;
13217
- } else {
13218
- applyDecision(part, decision, filter.name, i, text);
13488
+ checkpoint("finalizeMessages");
13489
+ injectMessageIds(state, config, output.messages, compressionPriorities);
13490
+ hideFailedCompressCalls(output.messages);
13491
+ stripStaleMetadata(output.messages);
13492
+ dropEmptyMessages(output.messages);
13493
+ const smartPlanEnabled = applyCompressOverrides(
13494
+ config,
13495
+ state.modelProviderID,
13496
+ state.modelID
13497
+ ).compress.smartPlanRequired;
13498
+ if (state.sessionId && smartPlanEnabled === true) {
13499
+ recordVisibleMessages(state.sessionId, output.messages);
13500
+ }
13501
+ checkpoint("postTokens");
13502
+ const postTokens = getCurrentTokenUsage(state, output.messages);
13503
+ checkpoint("budgetGuard");
13504
+ if (postTokens !== void 0 && effectiveLimit) {
13505
+ const budget = effectiveLimit.limit - (state.systemPromptTokens ?? 0) - OUTPUT_RESERVE_TOKENS;
13506
+ if (postTokens > budget) {
13507
+ logger.error(
13508
+ "ACP hard guard: context exceeds model budget after in-flight reduction",
13509
+ {
13510
+ session: state.sessionId,
13511
+ postTokens,
13512
+ budget,
13513
+ contextLimit: effectiveLimit.limit,
13514
+ contextLimitSource: effectiveLimit.source,
13515
+ hint: "request will likely be rejected; run /compact or start a new session"
13516
+ }
13517
+ );
13219
13518
  }
13220
13519
  }
13520
+ logger.info("Chat transform complete", {
13521
+ session: state.sessionId,
13522
+ model: state.modelID,
13523
+ messages: output.messages.length,
13524
+ prePruneTokens,
13525
+ postTokens,
13526
+ contextLimit: effectiveLimit?.limit,
13527
+ contextLimitSource: effectiveLimit?.source,
13528
+ usagePct: postTokens !== void 0 && effectiveLimit ? `${(postTokens / effectiveLimit.limit * 100).toFixed(1)}%` : void 0,
13529
+ nudged: state.nudges.shouldInjectThisTurn
13530
+ });
13531
+ checkpoint("saveContext");
13532
+ if (diagnostic) {
13533
+ diagnostic.counts.blocks = state.prune.messages.blocksById.size;
13534
+ diagnostic.counts.activeBlocks = state.prune.messages.activeBlockIds.size;
13535
+ }
13536
+ if (state.sessionId) {
13537
+ await logger.saveContext(state.sessionId, output.messages);
13538
+ }
13539
+ } catch (error) {
13540
+ diagnostic?.fail("transform");
13541
+ throw error;
13542
+ } finally {
13543
+ timeline?.end();
13221
13544
  }
13222
- }
13223
- if (result.partsFiltered > 0) {
13224
- logger.info("Message filters applied", {
13225
- filtersRun: allFilters.length,
13226
- partsFiltered: result.partsFiltered,
13227
- partsDropped: result.partsDropped,
13228
- partsModified: result.partsModified
13229
- });
13230
- }
13231
- return result;
13545
+ };
13232
13546
  }
13233
13547
 
13234
- // src/messages/filter/builtin/omo-system-reminder.ts
13235
- var SYSTEM_REMINDER_OPEN = "<system-reminder>";
13236
- var OMO_MARKER = "<!-- OMO_INTERNAL_INITIATOR -->";
13237
- var PAIRED_BLOCK_RE = /<system-reminder>[\s\S]*?<\/system-reminder>\s*<!-- OMO_INTERNAL_INITIATOR -->/g;
13238
- var LONE_REMINDER_RE = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
13239
- var LONE_MARKER_RE = /<!-- OMO_INTERNAL_INITIATOR -->/g;
13240
- var OMO_SYSTEM_REMINDER_FILTER = {
13241
- name: "omo-system-reminder",
13242
- version: "1.3.0",
13243
- description: "Keep recent OMO <system-reminder> messages; for older ones, strip blocks but preserve user content",
13244
- keepLastOnly: true,
13245
- keepLast: 2,
13246
- filter(ctx) {
13247
- if (ctx.role !== "user") return { action: "keep" };
13248
- if (!ctx.text.includes(SYSTEM_REMINDER_OPEN) && !ctx.text.includes(OMO_MARKER)) {
13249
- return { action: "keep" };
13250
- }
13251
- let modified = ctx.text;
13252
- let removedBlocks = 0;
13253
- modified = modified.replace(PAIRED_BLOCK_RE, () => {
13254
- removedBlocks++;
13255
- return "";
13256
- });
13257
- modified = modified.replace(LONE_REMINDER_RE, () => {
13258
- removedBlocks++;
13259
- return "";
13260
- });
13261
- modified = modified.replace(LONE_MARKER_RE, "");
13262
- modified = modified.replace(/\n{3,}/g, "\n\n").trim();
13263
- if (modified.length === 0) {
13264
- return { action: "drop", reason: `Pure OMO system-reminder (${removedBlocks} block(s), no user content)` };
13265
- }
13266
- return {
13267
- action: "modify",
13268
- text: modified,
13269
- reason: `Stripped ${removedBlocks} OMO system-reminder block(s), preserved user content (${modified.length} chars)`
13270
- };
13271
- }
13272
- };
13273
-
13274
- // src/messages/filter/builtin/omo-todo-continuation.ts
13275
- var TODO_MARKER = "[SYSTEM DIRECTIVE";
13276
- var TODO_CONTINUATION = "TODO CONTINUATION";
13277
- var OMO_TODO_FILTER = {
13278
- name: "omo-todo-continuation",
13279
- version: "1.0.0",
13280
- description: "Keep only the latest OMO TODO CONTINUATION directive, drop earlier occurrences",
13281
- keepLastOnly: true,
13282
- filter(ctx) {
13283
- if (ctx.role !== "user") return { action: "keep" };
13284
- if (!ctx.text.includes(TODO_MARKER) || !ctx.text.includes(TODO_CONTINUATION)) {
13285
- return { action: "keep" };
13286
- }
13287
- return { action: "drop", reason: "TODO CONTINUATION directive" };
13288
- }
13289
- };
13290
-
13291
- // src/messages/filter/builtin/omo-context.ts
13292
- var OMO_MARKER2 = "<!-- OMO_INTERNAL_INITIATOR -->";
13293
- var OMO_CONTEXT_FILTER = {
13294
- name: "omo-context",
13295
- version: "1.0.0",
13296
- description: "Keep only the latest OMO [CONTEXT] injection, drop earlier occurrences",
13297
- keepLastOnly: true,
13298
- filter(ctx) {
13299
- if (ctx.role !== "user") return { action: "keep" };
13300
- if (!ctx.text.includes(OMO_MARKER2)) return { action: "keep" };
13301
- const stripped = ctx.text.trimStart();
13302
- if (!stripped.startsWith("[CONTEXT]") && !stripped.startsWith("CONTEXT:")) {
13303
- return { action: "keep" };
13548
+ // src/commands/context.ts
13549
+ function analyzeTokens(state, messages) {
13550
+ const breakdown = {
13551
+ system: 0,
13552
+ user: 0,
13553
+ assistant: 0,
13554
+ tools: 0,
13555
+ toolCount: 0,
13556
+ toolsInContextCount: 0,
13557
+ prunedTokens: state.stats.totalPruneTokens,
13558
+ prunedToolCount: 0,
13559
+ prunedMessageCount: 0,
13560
+ total: 0
13561
+ };
13562
+ let firstAssistant;
13563
+ for (const msg of messages) {
13564
+ if (msg.info.role === "assistant") {
13565
+ const assistantInfo = msg.info;
13566
+ if (assistantInfo.tokens?.input > 0 || assistantInfo.tokens?.cache?.read > 0 || assistantInfo.tokens?.cache?.write > 0) {
13567
+ firstAssistant = assistantInfo;
13568
+ break;
13569
+ }
13304
13570
  }
13305
- return { action: "drop", reason: "OMO context injection" };
13306
13571
  }
13307
- };
13308
-
13309
- // src/messages/filter/builtin/omo-task-directive.ts
13310
- var OMO_MARKER3 = "<!-- OMO_INTERNAL_INITIATOR -->";
13311
- var OMO_TASK_FILTER = {
13312
- name: "omo-task-directive",
13313
- version: "1.0.0",
13314
- description: "Keep only the latest OMO TASK directive, drop earlier occurrences",
13315
- keepLastOnly: true,
13316
- filter(ctx) {
13317
- if (ctx.role !== "user") return { action: "keep" };
13318
- if (!ctx.text.includes(OMO_MARKER3)) return { action: "keep" };
13319
- const stripped = ctx.text.trimStart();
13320
- if (!stripped.startsWith("TASK:") && !stripped.startsWith("## TASK")) {
13321
- return { action: "keep" };
13572
+ let lastAssistant;
13573
+ for (let i = messages.length - 1; i >= 0; i--) {
13574
+ const msg = messages[i];
13575
+ if (msg.info.role === "assistant") {
13576
+ const assistantInfo = msg.info;
13577
+ if (assistantInfo.tokens?.output > 0) {
13578
+ lastAssistant = assistantInfo;
13579
+ break;
13580
+ }
13322
13581
  }
13323
- return { action: "drop", reason: "OMO task directive" };
13324
13582
  }
13325
- };
13326
-
13327
- // src/messages/filter/builtin/omo-mode-injection.ts
13328
- var XML_MODE_TAGS = [
13329
- { open: "<hyperplan-ultrawork-mode>", close: "</hyperplan-ultrawork-mode>" },
13330
- { open: "<ultrawork-mode>", close: "</ultrawork-mode>" }
13331
- ];
13332
- var BRACKET_MODE_PATTERNS = ["[search-mode]", "[analyze-mode]", "[ultrawork-mode]"];
13333
- function stripLeadingModeInjections(text) {
13334
- let current = text;
13335
- let strippedAny = false;
13336
- for (let iter = 0; iter < 5; iter++) {
13337
- current = current.trimStart();
13338
- let matched = false;
13339
- for (const { open, close } of XML_MODE_TAGS) {
13340
- if (current.startsWith(open)) {
13341
- const closeIdx = current.indexOf(close);
13342
- if (closeIdx !== -1) {
13343
- current = current.slice(closeIdx + close.length);
13344
- } else {
13345
- current = current.slice(open.length);
13583
+ const apiInput = lastAssistant?.tokens?.input || 0;
13584
+ const apiOutput = lastAssistant?.tokens?.output || 0;
13585
+ const apiReasoning = lastAssistant?.tokens?.reasoning || 0;
13586
+ const apiCacheRead = lastAssistant?.tokens?.cache?.read || 0;
13587
+ const apiCacheWrite = lastAssistant?.tokens?.cache?.write || 0;
13588
+ breakdown.total = apiInput + apiOutput + apiReasoning + apiCacheRead + apiCacheWrite;
13589
+ const userTextParts = [];
13590
+ const toolInputParts = [];
13591
+ const toolOutputParts = [];
13592
+ let firstUserText = "";
13593
+ let foundFirstUser = false;
13594
+ const allToolIds = /* @__PURE__ */ new Set();
13595
+ const activeToolIds = /* @__PURE__ */ new Set();
13596
+ const prunedToolIds = /* @__PURE__ */ new Set();
13597
+ const allMessageIds = /* @__PURE__ */ new Set();
13598
+ for (const msg of messages) {
13599
+ allMessageIds.add(msg.info.id);
13600
+ const parts = Array.isArray(msg.parts) ? msg.parts : [];
13601
+ const isCompacted = isMessageCompacted(state, msg);
13602
+ const pruneEntry = state.prune.messages.byMessageId.get(msg.info.id);
13603
+ const isMessagePruned = !!pruneEntry && pruneEntry.activeBlockIds.length > 0;
13604
+ const isIgnoredUser = isIgnoredUserMessage(msg);
13605
+ for (const part of parts) {
13606
+ if (part.type === "tool") {
13607
+ const toolPart = part;
13608
+ if (toolPart.callID) {
13609
+ allToolIds.add(toolPart.callID);
13610
+ if (!isCompacted) {
13611
+ activeToolIds.add(toolPart.callID);
13612
+ }
13613
+ if (isMessagePruned) {
13614
+ prunedToolIds.add(toolPart.callID);
13615
+ }
13346
13616
  }
13347
- matched = true;
13348
- break;
13349
- }
13350
- }
13351
- if (!matched) {
13352
- for (const pattern of BRACKET_MODE_PATTERNS) {
13353
- if (current.startsWith(pattern)) {
13354
- current = current.slice(pattern.length);
13355
- matched = true;
13356
- break;
13617
+ if (!isCompacted) {
13618
+ if (toolPart.state?.input) {
13619
+ const inputStr = typeof toolPart.state.input === "string" ? toolPart.state.input : JSON.stringify(toolPart.state.input);
13620
+ toolInputParts.push(inputStr);
13621
+ }
13622
+ const outputStr = extractCompletedToolOutput(toolPart);
13623
+ if (outputStr !== void 0) {
13624
+ toolOutputParts.push(outputStr);
13625
+ }
13626
+ }
13627
+ } else if (part.type === "text" && msg.info.role === "user" && !isCompacted && !isIgnoredUser) {
13628
+ const textPart = part;
13629
+ const text = textPart.text || "";
13630
+ userTextParts.push(text);
13631
+ if (!foundFirstUser) {
13632
+ firstUserText += text;
13357
13633
  }
13358
13634
  }
13359
13635
  }
13360
- if (matched) {
13361
- strippedAny = true;
13362
- } else {
13363
- break;
13636
+ if (msg.info.role === "user" && !isIgnoredUser && !foundFirstUser) {
13637
+ foundFirstUser = true;
13364
13638
  }
13365
13639
  }
13366
- return strippedAny ? current.trim() : null;
13367
- }
13368
- var OMO_MODE_FILTER = {
13369
- name: "omo-mode-injection",
13370
- version: "1.1.0",
13371
- description: "Strip OMO mode injection blocks (<ultrawork-mode>...</ultrawork-mode>, [search-mode], etc.) from user messages, preserving user content",
13372
- filter(ctx) {
13373
- if (ctx.role !== "user") return { action: "keep" };
13374
- const remaining = stripLeadingModeInjections(ctx.text);
13375
- if (remaining === null) return { action: "keep" };
13376
- if (remaining.length === 0) {
13377
- return { action: "drop", reason: "OMO mode injection (no user content after stripping)" };
13640
+ const toolsInContextCount = [...activeToolIds].filter((id) => !prunedToolIds.has(id)).length;
13641
+ let prunedMessageCount = 0;
13642
+ for (const [id, entry] of state.prune.messages.byMessageId) {
13643
+ if (allMessageIds.has(id) && entry.activeBlockIds.length > 0) {
13644
+ prunedMessageCount++;
13378
13645
  }
13379
- return {
13380
- action: "modify",
13381
- text: remaining,
13382
- reason: "Stripped OMO mode injection block(s), preserved user content"
13383
- };
13384
13646
  }
13385
- };
13386
-
13387
- // src/messages/filter/builtin/index.ts
13388
- var BUILTIN_FILTERS = [
13389
- OMO_SYSTEM_REMINDER_FILTER,
13390
- OMO_TODO_FILTER,
13391
- OMO_CONTEXT_FILTER,
13392
- OMO_TASK_FILTER,
13393
- OMO_MODE_FILTER
13394
- ];
13395
- function ensureBuiltinFiltersRegistered() {
13396
- for (const filter of BUILTIN_FILTERS) {
13397
- if (!getMessageFilter(filter.name)) {
13398
- registerMessageFilter(filter);
13399
- }
13647
+ breakdown.toolCount = allToolIds.size;
13648
+ breakdown.toolsInContextCount = toolsInContextCount;
13649
+ breakdown.prunedToolCount = prunedToolIds.size;
13650
+ breakdown.prunedMessageCount = prunedMessageCount;
13651
+ const firstUserTokens = countTokens2(firstUserText);
13652
+ breakdown.user = countTokens2(userTextParts.join("\n"));
13653
+ const toolInputTokens = countTokens2(toolInputParts.join("\n"));
13654
+ const toolOutputTokens = countTokens2(toolOutputParts.join("\n"));
13655
+ if (firstAssistant) {
13656
+ const firstInput = (firstAssistant.tokens?.input || 0) + (firstAssistant.tokens?.cache?.read || 0) + (firstAssistant.tokens?.cache?.write || 0);
13657
+ breakdown.system = Math.max(0, firstInput - firstUserTokens);
13658
+ }
13659
+ breakdown.tools = toolInputTokens + toolOutputTokens;
13660
+ breakdown.assistant = Math.max(
13661
+ 0,
13662
+ breakdown.total - breakdown.system - breakdown.user - breakdown.tools
13663
+ );
13664
+ return breakdown;
13665
+ }
13666
+ function createBar(value, maxValue, width, char = "\u2588") {
13667
+ if (maxValue === 0) return "";
13668
+ const filled = Math.round(value / maxValue * width);
13669
+ const bar = char.repeat(Math.max(0, filled));
13670
+ return bar;
13671
+ }
13672
+ function formatContextMessage(breakdown) {
13673
+ const lines = [];
13674
+ const barWidth = 30;
13675
+ const toolsLabel = `Tools (${breakdown.toolsInContextCount})`;
13676
+ const categories = [
13677
+ { label: "System", value: breakdown.system, char: "\u2588" },
13678
+ { label: "User", value: breakdown.user, char: "\u2593" },
13679
+ { label: "Assistant", value: breakdown.assistant, char: "\u2592" },
13680
+ { label: toolsLabel, value: breakdown.tools, char: "\u2591" }
13681
+ ];
13682
+ const maxLabelLen = Math.max(...categories.map((c) => c.label.length));
13683
+ 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");
13684
+ lines.push("\u2502 ACP Context Analysis \u2502");
13685
+ 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");
13686
+ lines.push("");
13687
+ lines.push("Session Context Breakdown:");
13688
+ lines.push("\u2500".repeat(60));
13689
+ lines.push("");
13690
+ for (const cat of categories) {
13691
+ const bar = createBar(cat.value, breakdown.total, barWidth, cat.char);
13692
+ const percentage = breakdown.total > 0 ? (cat.value / breakdown.total * 100).toFixed(1) : "0.0";
13693
+ const labelWithPct = `${cat.label.padEnd(maxLabelLen)} ${percentage.padStart(5)}% `;
13694
+ const valueStr = formatTokenCount(cat.value).padStart(13);
13695
+ lines.push(`${labelWithPct}\u2502${bar.padEnd(barWidth)}\u2502${valueStr}`);
13696
+ }
13697
+ lines.push("");
13698
+ lines.push("\u2500".repeat(60));
13699
+ lines.push("");
13700
+ lines.push("Summary:");
13701
+ if (breakdown.prunedTokens > 0) {
13702
+ const withoutPruning = breakdown.total + breakdown.prunedTokens;
13703
+ const pruned = [];
13704
+ if (breakdown.prunedToolCount > 0) pruned.push(`${breakdown.prunedToolCount} tools`);
13705
+ if (breakdown.prunedMessageCount > 0)
13706
+ pruned.push(`${breakdown.prunedMessageCount} messages`);
13707
+ lines.push(
13708
+ ` Pruned: ${pruned.join(", ")} (~${formatTokenCount(breakdown.prunedTokens)})`
13709
+ );
13710
+ lines.push(` Current context: ~${formatTokenCount(breakdown.total)}`);
13711
+ lines.push(` Without ACP: ~${formatTokenCount(withoutPruning)}`);
13712
+ } else {
13713
+ lines.push(` Current context: ~${formatTokenCount(breakdown.total)}`);
13400
13714
  }
13715
+ lines.push("");
13716
+ return lines.join("\n");
13717
+ }
13718
+ async function handleContextCommand(ctx) {
13719
+ const { client, state, logger, sessionId, messages } = ctx;
13720
+ const breakdown = analyzeTokens(state, messages);
13721
+ const message = formatContextMessage(breakdown);
13722
+ const params = getCurrentParams(state, messages, logger);
13723
+ await sendIgnoredMessage(client, sessionId, message, params, logger);
13401
13724
  }
13402
13725
 
13403
- // src/gc/merge.ts
13404
- function collectActiveOldGenBlocks(state, maxOldGenSummaryLength) {
13405
- const blocks = [];
13406
- const ids = Array.from(state.prune.messages.activeBlockIds).sort((a, b) => a - b);
13407
- for (const id of ids) {
13408
- const block = state.prune.messages.blocksById.get(id);
13409
- if (!block || !block.active) continue;
13410
- if (block.generation === "old" || block.generation === void 0 || block.summary.length > maxOldGenSummaryLength) {
13411
- blocks.push(block);
13726
+ // src/commands/stats.ts
13727
+ async function handleStatsCommand(ctx) {
13728
+ const report = buildStatusReport(
13729
+ { state: ctx.state, config: ctx.config },
13730
+ ctx.messages
13731
+ );
13732
+ const text = `[ACP Status]
13733
+ ${report}`;
13734
+ await sendIgnoredMessage(
13735
+ ctx.client,
13736
+ ctx.sessionId,
13737
+ text,
13738
+ {
13739
+ providerId: ctx.userInfo?.providerId,
13740
+ modelId: ctx.userInfo?.modelId,
13741
+ agent: ctx.userInfo?.agent,
13742
+ variant: ctx.userInfo?.variant
13743
+ },
13744
+ ctx.logger
13745
+ );
13746
+ }
13747
+
13748
+ // src/commands/export.ts
13749
+ import * as fs2 from "fs/promises";
13750
+ import { existsSync as existsSync7 } from "fs";
13751
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join7, resolve } from "path";
13752
+ var ALL_TIERS = [1, 2, 3];
13753
+ var TIER_NAMES = {
13754
+ 1: "Tier 1 \u2014 Capture",
13755
+ 2: "Tier 2 \u2014 Distilled",
13756
+ 3: "Tier 3 \u2014 Condensed"
13757
+ };
13758
+ function parseExportArgs(rawArgs) {
13759
+ const options = {
13760
+ outputPath: "",
13761
+ // "" sentinel => default path resolved later
13762
+ tiers: /* @__PURE__ */ new Set(),
13763
+ includeMetadata: true,
13764
+ append: false
13765
+ };
13766
+ const tokens = tokenize2(rawArgs);
13767
+ let i = 0;
13768
+ while (i < tokens.length) {
13769
+ const tok = tokens[i];
13770
+ const [flag, inlineValue] = splitFlag(tok);
13771
+ switch (flag) {
13772
+ case "--output":
13773
+ case "-o": {
13774
+ const value = inlineValue ?? tokens[i + 1];
13775
+ if (value === void 0) {
13776
+ throw new Error("--output requires a path (use `-` for stdout)");
13777
+ }
13778
+ options.outputPath = value;
13779
+ i += inlineValue !== void 0 ? 1 : 2;
13780
+ break;
13781
+ }
13782
+ case "--tier":
13783
+ case "-t": {
13784
+ const value = inlineValue ?? tokens[i + 1];
13785
+ if (value === void 0) {
13786
+ throw new Error("--tier requires a value (e.g. t2,t3 or all)");
13787
+ }
13788
+ options.tiers = parseTiers(value);
13789
+ i += inlineValue !== void 0 ? 1 : 2;
13790
+ break;
13791
+ }
13792
+ case "--no-metadata":
13793
+ if (inlineValue !== void 0) {
13794
+ throw new Error("--no-metadata does not take a value");
13795
+ }
13796
+ options.includeMetadata = false;
13797
+ i += 1;
13798
+ break;
13799
+ case "--metadata":
13800
+ if (inlineValue !== void 0) {
13801
+ throw new Error("--metadata does not take a value");
13802
+ }
13803
+ options.includeMetadata = true;
13804
+ i += 1;
13805
+ break;
13806
+ case "--append":
13807
+ if (inlineValue !== void 0) {
13808
+ throw new Error("--append does not take a value");
13809
+ }
13810
+ options.append = true;
13811
+ i += 1;
13812
+ break;
13813
+ case "--stdout":
13814
+ if (inlineValue !== void 0) {
13815
+ throw new Error("--stdout does not take a value");
13816
+ }
13817
+ options.outputPath = "-";
13818
+ i += 1;
13819
+ break;
13820
+ default:
13821
+ throw new Error(
13822
+ `Unknown flag: ${tok}. Supported: --output, --tier, --no-metadata, --append, --stdout.`
13823
+ );
13412
13824
  }
13413
13825
  }
13414
- return blocks;
13826
+ return options;
13415
13827
  }
13416
- function extractSummaryBody(summary) {
13417
- let body = summary;
13418
- const headerPrefix = COMPRESSED_BLOCK_HEADER + "\n";
13419
- if (body.startsWith(headerPrefix)) {
13420
- body = body.slice(headerPrefix.length);
13828
+ function tokenize2(input) {
13829
+ const tokens = [];
13830
+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
13831
+ let m;
13832
+ while ((m = re.exec(input)) !== null) {
13833
+ tokens.push(m[1] ?? m[2] ?? m[3]);
13421
13834
  }
13422
- body = body.replace(/\n]*>b\d+<\/acp-message-id>$/, "");
13423
- return body.trim();
13835
+ return tokens;
13424
13836
  }
13425
- function truncateMergedSummary(merged, maxLength) {
13426
- if (merged.length <= maxLength) return merged;
13427
- const blocks = merged.split("\n---\n");
13428
- const headers = blocks.map((b) => b.split("\n")[0] ?? "").filter((h) => h.trim().length > 0);
13429
- const marker = "\n...\n[merged and truncated by batch cleanup]";
13430
- const budget = Math.max(0, maxLength - marker.length);
13431
- const headerJoin = headers.join("\n");
13432
- if (headerJoin.length <= budget) {
13433
- return headerJoin + marker;
13434
- }
13435
- return headerJoin.slice(0, budget) + marker;
13837
+ function splitFlag(tok) {
13838
+ const eq = tok.indexOf("=");
13839
+ if (eq === -1) return [tok, void 0];
13840
+ return [tok.slice(0, eq), tok.slice(eq + 1)];
13436
13841
  }
13437
- function mergeMarkedBlocks(state, markedIds, maxMergedLength) {
13438
- const sortedIds = [...new Set(markedIds)].filter(
13439
- (id) => Number.isInteger(id) && id > 0
13440
- ).sort((a, b) => a - b);
13441
- const sourceBlocks = [];
13442
- for (const id of sortedIds) {
13443
- const block = state.prune.messages.blocksById.get(id);
13444
- if (!block || !block.active) continue;
13445
- if (!sourceBlocks.some((b) => b.blockId === id)) {
13446
- sourceBlocks.push(block);
13447
- }
13448
- }
13449
- if (sourceBlocks.length < 2) {
13450
- return { mergedCount: 0, savedTokens: 0 };
13451
- }
13452
- const messagesState = state.prune.messages;
13453
- const newBlockId = allocateBlockId(state);
13454
- const newRunId = allocateRunId(state);
13455
- const bodies = sourceBlocks.map((block) => extractSummaryBody(block.summary));
13456
- const mergedRaw = bodies.join("\n---\n");
13457
- const mergedBody = truncateMergedSummary(mergedRaw, maxMergedLength);
13458
- const newSummary = wrapCompressedSummary(newBlockId, mergedBody);
13459
- const newSummaryTokens = countTokens2(newSummary);
13460
- const oldest = sourceBlocks[0];
13461
- const newest = sourceBlocks[sourceBlocks.length - 1];
13462
- const effectiveMessageIds = /* @__PURE__ */ new Set();
13463
- const effectiveToolIds = /* @__PURE__ */ new Set();
13464
- for (const block of sourceBlocks) {
13465
- for (const id of block.effectiveMessageIds) effectiveMessageIds.add(id);
13466
- for (const id of block.effectiveToolIds) effectiveToolIds.add(id);
13467
- }
13468
- const sourceIds = sourceBlocks.map((b) => b.blockId);
13469
- const createdAt2 = Date.now();
13470
- const mergedBlock = {
13471
- blockId: newBlockId,
13472
- runId: newRunId,
13473
- active: true,
13474
- deactivatedByUser: false,
13475
- compressedTokens: 0,
13476
- summaryTokens: newSummaryTokens,
13477
- durationMs: 0,
13478
- mode: "range",
13479
- topic: "Batch merge cleanup",
13480
- batchTopic: "Batch merge cleanup",
13481
- startId: oldest.startId,
13482
- endId: newest.endId,
13483
- anchorMessageId: oldest.anchorMessageId,
13484
- compressMessageId: "",
13485
- compressCallId: void 0,
13486
- includedBlockIds: [...sourceIds],
13487
- consumedBlockIds: [...sourceIds],
13488
- parentBlockIds: [],
13489
- directMessageIds: [],
13490
- directToolIds: [],
13491
- effectiveMessageIds: [...effectiveMessageIds],
13492
- effectiveToolIds: [...effectiveToolIds],
13493
- createdAt: createdAt2,
13494
- summary: newSummary,
13495
- survivedCount: 0,
13496
- generation: "old"
13497
- };
13498
- const now = Date.now();
13499
- for (const block of sourceBlocks) {
13500
- block.active = false;
13501
- block.deactivatedAt = now;
13502
- block.deactivatedByBlockId = newBlockId;
13503
- if (!block.parentBlockIds.includes(newBlockId)) {
13504
- block.parentBlockIds.push(newBlockId);
13505
- }
13506
- messagesState.activeBlockIds.delete(block.blockId);
13507
- const mappedId = messagesState.activeByAnchorMessageId.get(block.anchorMessageId);
13508
- if (mappedId === block.blockId) {
13509
- messagesState.activeByAnchorMessageId.delete(block.anchorMessageId);
13510
- }
13511
- }
13512
- messagesState.blocksById.set(newBlockId, mergedBlock);
13513
- messagesState.activeBlockIds.add(newBlockId);
13514
- messagesState.activeByAnchorMessageId.set(mergedBlock.anchorMessageId, newBlockId);
13515
- for (const messageId of effectiveMessageIds) {
13516
- const entry = messagesState.byMessageId.get(messageId);
13517
- if (!entry) continue;
13518
- entry.activeBlockIds = entry.activeBlockIds.filter((id) => !sourceIds.includes(id));
13519
- if (!entry.activeBlockIds.includes(newBlockId)) {
13520
- entry.activeBlockIds.push(newBlockId);
13521
- }
13522
- if (!entry.allBlockIds.includes(newBlockId)) {
13523
- entry.allBlockIds.push(newBlockId);
13842
+ function parseTiers(raw) {
13843
+ const lower = raw.trim().toLowerCase();
13844
+ if (lower === "all") return new Set(ALL_TIERS);
13845
+ const parts = lower.split(",").map((p) => p.trim()).filter((p) => p.length > 0);
13846
+ const result = /* @__PURE__ */ new Set();
13847
+ for (const part of parts) {
13848
+ const digits = part.replace(/^t/i, "");
13849
+ const n = Number(digits);
13850
+ if (!Number.isInteger(n) || n < 1 || n > 3) {
13851
+ throw new Error(
13852
+ `Invalid tier "${part}". Expected t1, t2, t3, a combination (t2,t3), or "all".`
13853
+ );
13524
13854
  }
13855
+ result.add(n);
13525
13856
  }
13526
- for (const id of sourceIds) {
13527
- messagesState.markedForCleanup.delete(id);
13528
- }
13529
- const sourceTokens = sourceBlocks.reduce(
13530
- (sum, block) => sum + (block.summaryTokens || Math.round(block.summary.length / 4)),
13531
- 0
13532
- );
13533
- const savedTokens = Math.max(0, sourceTokens - newSummaryTokens);
13534
- bumpPruneStructureVersion(messagesState);
13535
- return { mergedCount: sourceBlocks.length, savedTokens };
13536
- }
13537
- function runBatchCleanup(state, config, logger, messages) {
13538
- const noop = {
13539
- tier: 0,
13540
- action: "none",
13541
- mergedCount: 0,
13542
- savedTokens: 0
13543
- };
13544
- const effective = resolveEffectiveContextLimit(state, config);
13545
- if (!effective) {
13546
- return noop;
13547
- }
13548
- const currentTokens = getCurrentTokenUsage(state, messages);
13549
- if (currentTokens < effective.limit) {
13550
- return noop;
13551
- }
13552
- const maxMergedLength = config.gc.maxOldGenSummaryLength;
13553
- const oldGenBlocks = collectActiveOldGenBlocks(state, maxMergedLength);
13554
- if (oldGenBlocks.length < 2) {
13555
- return noop;
13556
- }
13557
- const ids = oldGenBlocks.map((b) => b.blockId);
13558
- const result = mergeMarkedBlocks(state, ids, maxMergedLength);
13559
- if (result.mergedCount === 0) {
13560
- return noop;
13857
+ if (result.size === 0) {
13858
+ throw new Error(`Invalid tier "${raw}". Expected t1, t2, t3, or "all".`);
13561
13859
  }
13562
- logger.info("Batch cleanup force fallback (100%): merged old-gen blocks", {
13563
- mergedCount: result.mergedCount,
13564
- savedTokens: result.savedTokens,
13565
- currentTokens,
13566
- contextLimit: effective.limit,
13567
- contextLimitSource: effective.source
13568
- });
13569
- return {
13570
- tier: 3,
13571
- action: "merge",
13572
- mergedCount: result.mergedCount,
13573
- savedTokens: result.savedTokens
13574
- };
13860
+ return result;
13575
13861
  }
13576
-
13577
- // src/hooks.ts
13578
- var INTERNAL_AGENT_SIGNATURES = [
13579
- "You are a title generator",
13580
- "You are a helpful AI assistant tasked with summarizing conversations",
13581
- "You are an anchored context summarization assistant for coding sessions",
13582
- "Summarize what was done in this conversation"
13583
- ];
13584
- var INTERNAL_AGENT_NAMES = /* @__PURE__ */ new Set(["title", "summary", "compaction"]);
13585
- function isInternalAgentRequest(messages) {
13586
- const lastUserMessage = getLastUserMessage(messages);
13587
- if (!lastUserMessage) {
13588
- return false;
13589
- }
13590
- const agent = lastUserMessage.info.agent;
13591
- return typeof agent === "string" && INTERNAL_AGENT_NAMES.has(agent);
13862
+ function resolveDefaultOutputPath(sessionId, cwd2) {
13863
+ const short = (sessionId || "session").slice(0, 8);
13864
+ return join7(cwd2, ".opencode", `acp-export-${short}.md`);
13592
13865
  }
13593
- function createSystemPromptHandler(registry4, logger, config, prompts) {
13594
- return async (input, output) => {
13595
- registry4.recordModelLimit(
13596
- input.model?.providerID,
13597
- input.model?.id,
13598
- input.model?.limit?.context
13599
- );
13600
- const state = input.sessionID ? registry4.get(input.sessionID) : void 0;
13601
- if (!state || state.isSubAgent && !config.allowSubAgents) {
13602
- return;
13603
- }
13604
- const systemText = output.system.join("\n");
13605
- if (INTERNAL_AGENT_SIGNATURES.some((sig) => systemText.includes(sig))) {
13606
- logger.info("Skipping ACP system prompt injection for internal agent");
13607
- return;
13608
- }
13609
- if (input.model?.limit?.context) {
13610
- const limit = input.model.limit.context;
13611
- const providerID = input.model?.providerID;
13612
- const modelID = input.model?.id;
13613
- const changed = state.modelContextLimit !== limit || providerID !== void 0 && state.modelProviderID !== providerID || modelID !== void 0 && state.modelID !== modelID;
13614
- state.modelContextLimit = limit;
13615
- if (providerID !== void 0) {
13616
- state.modelProviderID = providerID;
13617
- }
13618
- if (modelID !== void 0) {
13619
- state.modelID = modelID;
13620
- }
13621
- if (changed) {
13622
- saveSessionState(state, logger).catch(() => {
13623
- });
13624
- }
13625
- }
13626
- const effectivePermission = compressPermission(state, config);
13627
- if (effectivePermission === "deny") {
13628
- return;
13629
- }
13630
- prompts.reload();
13631
- const runtimePrompts = prompts.getRuntimePrompts();
13632
- const newPrompt = renderSystemPrompt(
13633
- runtimePrompts,
13634
- buildProtectedToolsExtension(config.compress.protectedTools),
13635
- state.isSubAgent && config.allowSubAgents
13636
- );
13637
- if (output.system.length > 0) {
13638
- output.system[output.system.length - 1] += "\n\n" + newPrompt;
13639
- } else {
13640
- output.system.push(newPrompt);
13866
+ function formatTokens2(n) {
13867
+ if (!Number.isFinite(n) || n <= 0) return "0";
13868
+ return n >= 1e3 ? `${(n / 1e3).toFixed(1)}K` : String(n);
13869
+ }
13870
+ function effectiveTokens(block) {
13871
+ return block.effectiveCompressedTokens ?? block.compressedTokens ?? 0;
13872
+ }
13873
+ function collectActiveBlocks(state) {
13874
+ const msgState = state.prune.messages;
13875
+ const blocks = [];
13876
+ for (const id of msgState.activeBlockIds) {
13877
+ const block = msgState.blocksById.get(id);
13878
+ if (block && block.active) {
13879
+ blocks.push(block);
13641
13880
  }
13881
+ }
13882
+ return blocks;
13883
+ }
13884
+ function filterByTier(blocks, tiers) {
13885
+ if (tiers.size === 0) return blocks;
13886
+ return blocks.filter((b) => tiers.has(b.tier ?? 1));
13887
+ }
13888
+ function tokenSpans(blocks) {
13889
+ return {
13890
+ effective: blocks.reduce((s, b) => s + effectiveTokens(b), 0),
13891
+ summary: blocks.reduce((s, b) => s + (b.summaryTokens || 0), 0)
13642
13892
  };
13643
13893
  }
13644
- function createChatMessageTransformHandler(client, registry4, logger, config, prompts, hostPermissions) {
13645
- return async (input, output) => {
13646
- const receivedMessages = Array.isArray(output.messages) ? output.messages.length : 0;
13647
- const messages = filterMessagesInPlace(output.messages);
13648
- if (messages.length !== receivedMessages) {
13649
- logger.warn("Skipping messages with unexpected shape during chat transform", {
13650
- received: receivedMessages,
13651
- usable: messages.length
13652
- });
13653
- }
13654
- if (isInternalAgentRequest(messages)) {
13655
- logger.debug("Skipping message transform for internal agent request");
13656
- return;
13657
- }
13658
- const lastUserMessage = getLastUserMessage(messages);
13659
- let state;
13660
- if (!lastUserMessage) {
13661
- state = createSessionState();
13662
- } else {
13663
- state = await registry4.getOrCreate(
13664
- client,
13665
- lastUserMessage.info.sessionID,
13666
- messages,
13667
- config
13668
- );
13669
- const requestModel = lastUserMessage.info.model;
13670
- let requestModelLimit = registry4.resolveModelLimit(
13671
- requestModel?.providerID,
13672
- requestModel?.modelID
13673
- );
13674
- if (requestModelLimit === void 0 && requestModel?.providerID && requestModel?.modelID) {
13675
- requestModelLimit = await registry4.hydrateAndResolve(
13676
- client,
13677
- requestModel.providerID,
13678
- requestModel.modelID
13679
- );
13680
- }
13681
- const prevModelID = state.modelID;
13682
- if (requestModelLimit !== void 0) {
13683
- state.modelContextLimit = requestModelLimit;
13684
- state.modelProviderID = requestModel?.providerID;
13685
- state.modelID = requestModel?.modelID;
13686
- } else if (
13687
- // [FIX #312 fallback] Catalog miss: we cannot CORRECT the
13688
- // limit, but we can tell when it belongs to a DIFFERENT model.
13689
- // Invalidate instead of letting every percentage threshold
13690
- // below run against the wrong window (#312's false positive).
13691
- // States persisted before this identity pair existed carry no
13692
- // identity and are treated as stale for the same reason.
13693
- // Consumers already tolerate undefined — fresh sessions run
13694
- // with it until the first system.transform sets the pair.
13695
- requestModel?.providerID && requestModel?.modelID && state.modelContextLimit !== void 0 && (state.modelProviderID !== requestModel.providerID || state.modelID !== requestModel.modelID)
13696
- ) {
13697
- state.modelContextLimit = void 0;
13698
- state.modelProviderID = requestModel.providerID;
13699
- state.modelID = requestModel.modelID;
13700
- }
13701
- if (requestModel?.modelID && requestModel.modelID !== prevModelID) {
13702
- logger.info("Model switched mid-session", {
13703
- session: state.sessionId,
13704
- from: prevModelID,
13705
- to: requestModel.modelID,
13706
- contextLimit: state.modelContextLimit
13707
- });
13708
- }
13709
- await updatePerTurnState(state, logger, messages);
13710
- if (state.modelContextLimit === void 0 && !state.noContextLimitWarned && requestModel?.providerID && requestModel?.modelID && registry4.resolveModelLimit(requestModel.providerID, requestModel.modelID) === void 0) {
13711
- state.noContextLimitWarned = true;
13712
- logger.warn(
13713
- 'Model reports no context window and the catalog has no entry for it; all percentage thresholds (min/max/emergency, GC) and the context-budget guard are disabled. Set the model limit in opencode.json (e.g. "limit": {"context": 262144, "output": 16384}) to enable them (also fixes the 32000 max_tokens fallback); an absolute compress.maxContextLimit in acp.jsonc only enables proactive nudges, not the guard.',
13714
- {
13715
- session: state.sessionId,
13716
- model: `${requestModel.providerID}/${requestModel.modelID}`
13717
- }
13894
+ function tierCounts(blocks) {
13895
+ const counts = {};
13896
+ for (const b of blocks) {
13897
+ const t = b.tier ?? 1;
13898
+ counts[t] = (counts[t] || 0) + 1;
13899
+ }
13900
+ return ALL_TIERS.filter((t) => counts[t]).map((t) => `T${t}: ${counts[t]}`).join(", ");
13901
+ }
13902
+ function renderExportMarkdown(params) {
13903
+ const { sessionId, generatedAt, blocks, tiers, includeMetadata } = params;
13904
+ const out = [];
13905
+ const tierFilterLabel = tiers.size === 0 ? "all" : ALL_TIERS.filter((t) => tiers.has(t)).map((t) => `T${t}`).join(", ");
13906
+ out.push("# ACP Session Export");
13907
+ out.push("");
13908
+ out.push(`- **Session**: \`${(sessionId || "unknown").slice(0, 16)}\``);
13909
+ out.push(`- **Generated**: ${generatedAt.toISOString()}`);
13910
+ out.push(`- **Blocks exported**: ${blocks.length}`);
13911
+ const breakdown = tierCounts(blocks);
13912
+ if (breakdown) {
13913
+ out.push(` - ${breakdown}`);
13914
+ }
13915
+ out.push(`- **Tiers**: ${tierFilterLabel}`);
13916
+ const span = tokenSpans(blocks);
13917
+ if (blocks.length > 0) {
13918
+ out.push(
13919
+ `- **Coverage**: ${formatTokens2(span.effective)} original \u2192 ${formatTokens2(span.summary)} summary`
13920
+ );
13921
+ }
13922
+ out.push("");
13923
+ out.push("---");
13924
+ out.push("");
13925
+ if (blocks.length === 0) {
13926
+ out.push("_No active compression blocks match the selected tiers._");
13927
+ out.push("");
13928
+ out.push(
13929
+ "Tip: run `/acp export --tier all` to include every active tier, or trigger a compression first."
13930
+ );
13931
+ return out.join("\n");
13932
+ }
13933
+ for (const tier of [3, 2, 1]) {
13934
+ const tierBlocks = blocks.filter((b) => (b.tier ?? 1) === tier).sort((a, b) => a.blockId - b.blockId);
13935
+ if (tierBlocks.length === 0) continue;
13936
+ out.push(`## ${TIER_NAMES[tier]}`);
13937
+ out.push("");
13938
+ for (const block of tierBlocks) {
13939
+ const topic = block.topic || block.batchTopic || "(no topic)";
13940
+ out.push(`### b${block.blockId} \u2014 ${topic}`);
13941
+ out.push("");
13942
+ if (includeMetadata) {
13943
+ const mode = block.mode ?? "range";
13944
+ const msgCount = block.effectiveMessageIds?.length ?? 0;
13945
+ const created = new Date(block.createdAt).toISOString();
13946
+ const age = block.survivedCount ?? 0;
13947
+ out.push(`- **Tier**: T${tier} \xB7 **Mode**: ${mode}`);
13948
+ out.push(`- **Messages**: ${msgCount} (effective)`);
13949
+ out.push(
13950
+ `- **Tokens**: ${formatTokens2(effectiveTokens(block))} \u2192 ${formatTokens2(block.summaryTokens || 0)} summary`
13718
13951
  );
13952
+ out.push(`- **Created**: ${created}`);
13953
+ out.push(`- **Age**: survived ${age} transform${age === 1 ? "" : "s"}`);
13954
+ out.push("");
13719
13955
  }
13956
+ const summary = (block.summary || "").trim() || "_(empty summary)_";
13957
+ out.push(summary);
13958
+ out.push("");
13959
+ out.push("---");
13960
+ out.push("");
13720
13961
  }
13721
- syncCompressPermissionState(state, config, hostPermissions, output.messages);
13722
- if (state.isSubAgent && !config.allowSubAgents) {
13723
- return;
13724
- }
13725
- stripHallucinations(output.messages);
13726
- const dropReasoningModel = lastUserMessage?.info?.model;
13727
- const reasoningConfig = applyCompressOverrides(
13728
- config,
13729
- dropReasoningModel?.providerID ?? state.modelProviderID,
13730
- dropReasoningModel?.modelID ?? state.modelID
13731
- ).compress.reasoning;
13732
- if (reasoningConfig?.drop !== false) {
13733
- const droppedReasoning = dropCompressReasoning(
13734
- output.messages,
13735
- reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13736
- );
13737
- if (droppedReasoning > 0) {
13738
- logger.debug("compress.reasoning: dropped oversized reasoning parts", {
13739
- dropped: droppedReasoning,
13740
- threshold: reasoningConfig?.threshold ?? DEFAULT_COMPRESS_REASONING.threshold
13741
- });
13742
- }
13743
- }
13744
- ensureBuiltinFiltersRegistered();
13745
- const effectiveLimit = resolveEffectiveContextLimit(state, config);
13746
- applyMessageFilters(output.messages, config.messageFilters, logger, {
13747
- sessionId: state.sessionId ?? "",
13748
- isSubAgent: state.isSubAgent,
13749
- modelContextLimit: effectiveLimit?.limit
13750
- });
13751
- cacheSystemPromptTokens(state, output.messages);
13752
- assignMessageRefs(state, output.messages);
13753
- const imagesConfig = config.compress.images ?? DEFAULT_COMPRESS_IMAGES;
13754
- if (imagesConfig.enabled) {
13755
- const archivedImages = archiveSessionImages(
13756
- state,
13757
- output.messages,
13758
- imagesConfig,
13759
- logger
13760
- );
13761
- if (archivedImages > 0) {
13762
- saveSessionState(state, logger).catch(() => {
13763
- });
13764
- }
13765
- pruneImageArchive(state, imagesConfig, logger);
13766
- }
13767
- const activeBlockCountBefore = state.prune.messages.activeBlockIds.size;
13768
- const compressionStateChanged = syncCompressionBlocks(state, logger, output.messages);
13769
- if (compressionStateChanged || state.prune.messages.activeBlockIds.size !== activeBlockCountBefore) {
13770
- saveSessionState(state, logger).catch(() => {
13771
- });
13962
+ }
13963
+ return out.join("\n");
13964
+ }
13965
+ async function handleExportCommand(ctx, args) {
13966
+ const { client, state, logger, sessionId } = ctx;
13967
+ let options;
13968
+ try {
13969
+ options = parseExportArgs(args);
13970
+ } catch (err) {
13971
+ const msg = err?.message ?? String(err);
13972
+ logger.warn("export: argument parse failed", { error: msg, args });
13973
+ await sendExportNotice(client, sessionId, ctx, `[ACP Export] ${msg}`);
13974
+ return;
13975
+ }
13976
+ const tiers = options.tiers;
13977
+ const allActive = collectActiveBlocks(state);
13978
+ const blocks = filterByTier(allActive, tiers);
13979
+ const generatedAt = /* @__PURE__ */ new Date();
13980
+ const markdown = renderExportMarkdown({
13981
+ sessionId,
13982
+ generatedAt,
13983
+ blocks,
13984
+ tiers,
13985
+ includeMetadata: options.includeMetadata
13986
+ });
13987
+ if (options.outputPath === "-") {
13988
+ await sendExportNotice(client, sessionId, ctx, markdown);
13989
+ return;
13990
+ }
13991
+ const cwd2 = ctx.workingDirectory || process.cwd();
13992
+ const targetPath = options.outputPath !== "" ? isAbsolute2(options.outputPath) ? options.outputPath : resolve(cwd2, options.outputPath) : resolveDefaultOutputPath(sessionId, cwd2);
13993
+ try {
13994
+ const dir = dirname3(targetPath);
13995
+ if (!existsSync7(dir)) {
13996
+ await fs2.mkdir(dir, { recursive: true });
13772
13997
  }
13773
- syncToolCache(state, config, logger, output.messages);
13774
- buildToolIdList(state, output.messages);
13775
- const batchResult = runBatchCleanup(state, config, logger, output.messages);
13776
- if (batchResult.mergedCount > 0) {
13777
- saveSessionState(state, logger).catch(() => {
13778
- });
13998
+ const flag = options.append ? "a" : "w";
13999
+ if (options.append && existsSync7(targetPath)) {
14000
+ await fs2.appendFile(targetPath, `
14001
+
14002
+ ---
14003
+
14004
+ ${markdown}`, "utf-8");
14005
+ } else {
14006
+ await fs2.writeFile(targetPath, markdown, { flag, encoding: "utf-8" });
13779
14007
  }
13780
- const prePruneTokens = getCurrentTokenUsage(state, output.messages);
13781
- const candidateMessages = config.compress.candidates === true ? output.messages.slice() : void 0;
13782
- prune(state, logger, config, output.messages);
13783
- hideConsumedCompressCalls(state, output.messages);
13784
- assignMessageRefs(state, output.messages);
13785
- const compressionPriorities = buildPriorityMap(config, state, output.messages);
13786
- prompts.reload();
13787
- injectCompressNudges(
13788
- state,
13789
- config,
13790
- logger,
13791
- output.messages,
13792
- prompts.getRuntimePrompts(),
13793
- compressionPriorities,
13794
- config.debug ? (text) => {
13795
- logger.debug(`[ACP Debug] Nudge injected:
13796
- ${text}`);
13797
- } : void 0,
13798
- prePruneTokens,
13799
- candidateMessages
14008
+ } catch (err) {
14009
+ const msg = err?.message ?? String(err);
14010
+ logger.warn("export: file write failed", { path: targetPath, error: msg });
14011
+ await sendExportNotice(
14012
+ client,
14013
+ sessionId,
14014
+ ctx,
14015
+ `[ACP Export] Failed to write \`${targetPath}\`: ${msg}`
13800
14016
  );
13801
- const emergencyTruncationEnabled = applyCompressOverrides(
13802
- config,
13803
- dropReasoningModel?.providerID ?? state.modelProviderID,
13804
- dropReasoningModel?.modelID ?? state.modelID
13805
- ).compress.emergencyTruncation;
13806
- if (emergencyTruncationEnabled === true) {
13807
- applyStickyTruncations(state, output.messages, logger);
13808
- const toolOutputsBefore = snapshotToolOutputs(output.messages);
13809
- truncateLargeToolOutputs(
13810
- state,
13811
- config,
13812
- logger,
13813
- output.messages.filter((message) => !isSyntheticMessage(message))
13814
- );
13815
- enforceContextBudget(state, config, logger, output.messages);
13816
- const frozenCount = recordStickyTruncations(
13817
- state,
13818
- output.messages,
13819
- toolOutputsBefore,
13820
- logger
13821
- );
13822
- if (frozenCount > 0) {
13823
- saveSessionState(state, logger).catch(() => {
13824
- });
13825
- }
13826
- }
13827
- injectMessageIds(state, config, output.messages, compressionPriorities);
13828
- hideFailedCompressCalls(output.messages);
13829
- stripStaleMetadata(output.messages);
13830
- dropEmptyMessages(output.messages);
13831
- const smartPlanEnabled = applyCompressOverrides(
13832
- config,
13833
- state.modelProviderID,
13834
- state.modelID
13835
- ).compress.smartPlanRequired;
13836
- if (state.sessionId && smartPlanEnabled === true) {
13837
- recordVisibleMessages(state.sessionId, output.messages);
13838
- }
13839
- const postTokens = getCurrentTokenUsage(state, output.messages);
13840
- if (postTokens !== void 0 && effectiveLimit) {
13841
- const budget = effectiveLimit.limit - (state.systemPromptTokens ?? 0) - OUTPUT_RESERVE_TOKENS;
13842
- if (postTokens > budget) {
13843
- logger.error(
13844
- "ACP hard guard: context exceeds model budget after in-flight reduction",
13845
- {
13846
- session: state.sessionId,
13847
- postTokens,
13848
- budget,
13849
- contextLimit: effectiveLimit.limit,
13850
- contextLimitSource: effectiveLimit.source,
13851
- hint: "request will likely be rejected; run /compact or start a new session"
13852
- }
13853
- );
13854
- }
13855
- }
13856
- logger.info("Chat transform complete", {
13857
- session: state.sessionId,
13858
- model: state.modelID,
13859
- messages: output.messages.length,
13860
- prePruneTokens,
13861
- postTokens,
13862
- contextLimit: effectiveLimit?.limit,
13863
- contextLimitSource: effectiveLimit?.source,
13864
- usagePct: postTokens !== void 0 && effectiveLimit ? `${(postTokens / effectiveLimit.limit * 100).toFixed(1)}%` : void 0,
13865
- nudged: state.nudges.shouldInjectThisTurn
13866
- });
13867
- if (state.sessionId) {
13868
- await logger.saveContext(state.sessionId, output.messages);
13869
- }
13870
- };
14017
+ return;
14018
+ }
14019
+ logger.info("export: wrote markdown", {
14020
+ path: targetPath,
14021
+ blocks: blocks.length,
14022
+ tiers: tiers.size ? [...tiers].sort().join(",") : "all"
14023
+ });
14024
+ const summary = formatExportSummary(targetPath, blocks, allActive, generatedAt);
14025
+ await sendExportNotice(client, sessionId, ctx, summary);
14026
+ }
14027
+ function formatExportSummary(path, exported, allActive, generatedAt) {
14028
+ const lines = [];
14029
+ lines.push("[ACP Export]");
14030
+ lines.push(`Wrote ${exported.length} block${exported.length === 1 ? "" : "s"} to:`);
14031
+ lines.push(` ${path}`);
14032
+ if (exported.length === 0) {
14033
+ lines.push("");
14034
+ lines.push(
14035
+ `No matching blocks (of ${allActive.length} active). Try \`/acp export --tier all\`.`
14036
+ );
14037
+ } else {
14038
+ lines.push("");
14039
+ lines.push(`Generated ${generatedAt.toISOString()}.`);
14040
+ lines.push(
14041
+ "Review, edit, and commit as project notes \u2014 export is user-driven, never auto-injected."
14042
+ );
14043
+ }
14044
+ return lines.join("\n");
14045
+ }
14046
+ async function sendExportNotice(client, sessionId, ctx, text) {
14047
+ await sendIgnoredMessage(client, sessionId, text, {}, ctx.logger);
13871
14048
  }
14049
+
14050
+ // src/hooks/command.ts
13872
14051
  function buildHelpText() {
13873
14052
  return [
13874
14053
  "[ACP] Available commands:",
@@ -13918,6 +14097,8 @@ function createCommandExecuteHandler(client, registry4, logger, config, workingD
13918
14097
  }
13919
14098
  };
13920
14099
  }
14100
+
14101
+ // src/hooks/event.ts
13921
14102
  function createEventHandler(registry4, logger) {
13922
14103
  return async (input) => {
13923
14104
  if (input.event?.type === "session.idle" || input.event?.type === "session.deleted") {
@@ -14334,32 +14515,45 @@ var AcpV2Plugin = Plugin.define({
14334
14515
  );
14335
14516
  const transformSystem = createSystemPromptHandler(registry4, logger, config, prompts);
14336
14517
  await ctx.session.hook("context", async (event) => {
14337
- const messages = await fetchV2SessionMessages(ctx, event.sessionID);
14338
- if (messages.length === 0) return;
14339
- const lastUser = [...messages].reverse().find((message) => message.info.role === "user");
14340
- if (lastUser?.info.role === "user") {
14341
- lastUser.info.agent = event.agent;
14342
- lastUser.info.model = {
14343
- providerID: event.model.providerID,
14344
- modelID: event.model.id
14518
+ await diagnoseContext(logger, event.sessionID, async (diagnostic) => {
14519
+ const timeline = diagnostic?.timeline("context", "fetchSessionMessages");
14520
+ const checkpoint = (stage) => timeline?.next(stage);
14521
+ const messages = await fetchV2SessionMessages(ctx, event.sessionID);
14522
+ checkpoint("prepareMessages");
14523
+ if (diagnostic) diagnostic.counts.inputMessages = messages.length;
14524
+ if (messages.length === 0) {
14525
+ diagnostic?.skip("empty_history");
14526
+ return;
14527
+ }
14528
+ const lastUser = [...messages].reverse().find((message) => message.info.role === "user");
14529
+ if (lastUser?.info.role === "user") {
14530
+ lastUser.info.agent = event.agent;
14531
+ lastUser.info.model = {
14532
+ providerID: event.model.providerID,
14533
+ modelID: event.model.id
14534
+ };
14535
+ lastUser.info.providerID = event.model.providerID;
14536
+ lastUser.info.modelID = event.model.id;
14537
+ }
14538
+ const output = { messages };
14539
+ checkpoint("transformMessages");
14540
+ await transformMessages({}, output);
14541
+ if (diagnostic) diagnostic.counts.outputMessages = output.messages.length;
14542
+ checkpoint("convertRequestMessages");
14543
+ event.messages = toV2RequestMessages(output.messages);
14544
+ checkpoint("transformSystem");
14545
+ const systemOutput = {
14546
+ system: event.system.map((part) => part.text)
14345
14547
  };
14346
- lastUser.info.providerID = event.model.providerID;
14347
- lastUser.info.modelID = event.model.id;
14348
- }
14349
- const output = { messages };
14350
- await transformMessages({}, output);
14351
- event.messages = toV2RequestMessages(output.messages);
14352
- const systemOutput = {
14353
- system: event.system.map((part) => part.text)
14354
- };
14355
- await transformSystem(
14356
- {
14357
- sessionID: event.sessionID,
14358
- model: asV2Model(event.model)
14359
- },
14360
- systemOutput
14361
- );
14362
- event.system = systemOutput.system.map((text) => ({ type: "text", text }));
14548
+ await transformSystem(
14549
+ {
14550
+ sessionID: event.sessionID,
14551
+ model: asV2Model(event.model)
14552
+ },
14553
+ systemOutput
14554
+ );
14555
+ event.system = systemOutput.system.map((text) => ({ type: "text", text }));
14556
+ });
14363
14557
  });
14364
14558
  const abort = new AbortController();
14365
14559
  const eventHandler = createEventHandler(registry4, logger);