@infituit/opencode-acp 2.0.0-alpha.3 → 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.3" : "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,
@@ -12403,6 +12403,65 @@ function renderSystemPrompt(prompts, protectedToolsExtension, subagent) {
12403
12403
  return [prompts.system.trim(), ...extensions].filter(Boolean).join("\n\n").replace(/\n([ \t]*\n)+/g, "\n\n").trim();
12404
12404
  }
12405
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
+
12406
12465
  // src/messages/truncate-tools.ts
12407
12466
  var TRUNCATION_MARKER = "[truncated for context space";
12408
12467
  var MIN_OUTPUT_TOKENS = 1e3;
@@ -12718,831 +12777,329 @@ function enforceContextBudget(state, config, logger, messages) {
12718
12777
  };
12719
12778
  }
12720
12779
 
12721
- // src/commands/context.ts
12722
- function analyzeTokens(state, messages) {
12723
- const breakdown = {
12724
- system: 0,
12725
- user: 0,
12726
- assistant: 0,
12727
- tools: 0,
12728
- toolCount: 0,
12729
- toolsInContextCount: 0,
12730
- prunedTokens: state.stats.totalPruneTokens,
12731
- prunedToolCount: 0,
12732
- prunedMessageCount: 0,
12733
- total: 0
12734
- };
12735
- let firstAssistant;
12736
- for (const msg of messages) {
12737
- if (msg.info.role === "assistant") {
12738
- const assistantInfo = msg.info;
12739
- if (assistantInfo.tokens?.input > 0 || assistantInfo.tokens?.cache?.read > 0 || assistantInfo.tokens?.cache?.write > 0) {
12740
- firstAssistant = assistantInfo;
12741
- break;
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
+ });
12742
12834
  }
12835
+ return "";
12743
12836
  }
12744
- }
12745
- let lastAssistant;
12746
- for (let i = messages.length - 1; i >= 0; i--) {
12747
- const msg = messages[i];
12748
- if (msg.info.role === "assistant") {
12749
- const assistantInfo = msg.info;
12750
- if (assistantInfo.tokens?.output > 0) {
12751
- lastAssistant = assistantInfo;
12752
- break;
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
+ });
12753
12848
  }
12849
+ return decision.text;
12754
12850
  }
12755
- }
12756
- const apiInput = lastAssistant?.tokens?.input || 0;
12757
- const apiOutput = lastAssistant?.tokens?.output || 0;
12758
- const apiReasoning = lastAssistant?.tokens?.reasoning || 0;
12759
- const apiCacheRead = lastAssistant?.tokens?.cache?.read || 0;
12760
- const apiCacheWrite = lastAssistant?.tokens?.cache?.write || 0;
12761
- breakdown.total = apiInput + apiOutput + apiReasoning + apiCacheRead + apiCacheWrite;
12762
- const userTextParts = [];
12763
- const toolInputParts = [];
12764
- const toolOutputParts = [];
12765
- let firstUserText = "";
12766
- let foundFirstUser = false;
12767
- const allToolIds = /* @__PURE__ */ new Set();
12768
- const activeToolIds = /* @__PURE__ */ new Set();
12769
- const prunedToolIds = /* @__PURE__ */ new Set();
12770
- const allMessageIds = /* @__PURE__ */ new Set();
12771
- for (const msg of messages) {
12772
- allMessageIds.add(msg.info.id);
12773
- const parts = Array.isArray(msg.parts) ? msg.parts : [];
12774
- const isCompacted = isMessageCompacted(state, msg);
12775
- const pruneEntry = state.prune.messages.byMessageId.get(msg.info.id);
12776
- const isMessagePruned = !!pruneEntry && pruneEntry.activeBlockIds.length > 0;
12777
- const isIgnoredUser = isIgnoredUserMessage(msg);
12778
- for (const part of parts) {
12779
- if (part.type === "tool") {
12780
- const toolPart = part;
12781
- if (toolPart.callID) {
12782
- allToolIds.add(toolPart.callID);
12783
- if (!isCompacted) {
12784
- activeToolIds.add(toolPart.callID);
12785
- }
12786
- if (isMessagePruned) {
12787
- prunedToolIds.add(toolPart.callID);
12788
- }
12789
- }
12790
- if (!isCompacted) {
12791
- if (toolPart.state?.input) {
12792
- const inputStr = typeof toolPart.state.input === "string" ? toolPart.state.input : JSON.stringify(toolPart.state.input);
12793
- toolInputParts.push(inputStr);
12794
- }
12795
- const outputStr = extractCompletedToolOutput(toolPart);
12796
- if (outputStr !== void 0) {
12797
- toolOutputParts.push(outputStr);
12851
+ return originalText;
12852
+ };
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
+ });
12798
12875
  }
12876
+ continue;
12799
12877
  }
12800
- } else if (part.type === "text" && msg.info.role === "user" && !isCompacted && !isIgnoredUser) {
12801
- const textPart = part;
12802
- const text = textPart.text || "";
12803
- userTextParts.push(text);
12804
- if (!foundFirstUser) {
12805
- firstUserText += text;
12806
- }
12878
+ if (decision.action === "keep") continue;
12879
+ current = applyDecision(part, decision, filter.name, i, current);
12880
+ filterCtx.text = current;
12807
12881
  }
12808
12882
  }
12809
- if (msg.info.role === "user" && !isIgnoredUser && !foundFirstUser) {
12810
- foundFirstUser = true;
12811
- }
12812
- }
12813
- const toolsInContextCount = [...activeToolIds].filter((id) => !prunedToolIds.has(id)).length;
12814
- let prunedMessageCount = 0;
12815
- for (const [id, entry] of state.prune.messages.byMessageId) {
12816
- if (allMessageIds.has(id) && entry.activeBlockIds.length > 0) {
12817
- prunedMessageCount++;
12818
- }
12819
- }
12820
- breakdown.toolCount = allToolIds.size;
12821
- breakdown.toolsInContextCount = toolsInContextCount;
12822
- breakdown.prunedToolCount = prunedToolIds.size;
12823
- breakdown.prunedMessageCount = prunedMessageCount;
12824
- const firstUserTokens = countTokens2(firstUserText);
12825
- breakdown.user = countTokens2(userTextParts.join("\n"));
12826
- const toolInputTokens = countTokens2(toolInputParts.join("\n"));
12827
- const toolOutputTokens = countTokens2(toolOutputParts.join("\n"));
12828
- if (firstAssistant) {
12829
- const firstInput = (firstAssistant.tokens?.input || 0) + (firstAssistant.tokens?.cache?.read || 0) + (firstAssistant.tokens?.cache?.write || 0);
12830
- breakdown.system = Math.max(0, firstInput - firstUserTokens);
12831
12883
  }
12832
- breakdown.tools = toolInputTokens + toolOutputTokens;
12833
- breakdown.assistant = Math.max(
12834
- 0,
12835
- breakdown.total - breakdown.system - breakdown.user - breakdown.tools
12836
- );
12837
- return breakdown;
12838
- }
12839
- function createBar(value, maxValue, width, char = "\u2588") {
12840
- if (maxValue === 0) return "";
12841
- const filled = Math.round(value / maxValue * width);
12842
- const bar = char.repeat(Math.max(0, filled));
12843
- return bar;
12844
- }
12845
- function formatContextMessage(breakdown) {
12846
- const lines = [];
12847
- const barWidth = 30;
12848
- const toolsLabel = `Tools (${breakdown.toolsInContextCount})`;
12849
- const categories = [
12850
- { label: "System", value: breakdown.system, char: "\u2588" },
12851
- { label: "User", value: breakdown.user, char: "\u2593" },
12852
- { label: "Assistant", value: breakdown.assistant, char: "\u2592" },
12853
- { label: toolsLabel, value: breakdown.tools, char: "\u2591" }
12854
- ];
12855
- const maxLabelLen = Math.max(...categories.map((c) => c.label.length));
12856
- lines.push("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E");
12857
- lines.push("\u2502 ACP Context Analysis \u2502");
12858
- lines.push("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");
12859
- lines.push("");
12860
- lines.push("Session Context Breakdown:");
12861
- lines.push("\u2500".repeat(60));
12862
- lines.push("");
12863
- for (const cat of categories) {
12864
- const bar = createBar(cat.value, breakdown.total, barWidth, cat.char);
12865
- const percentage = breakdown.total > 0 ? (cat.value / breakdown.total * 100).toFixed(1) : "0.0";
12866
- const labelWithPct = `${cat.label.padEnd(maxLabelLen)} ${percentage.padStart(5)}% `;
12867
- const valueStr = formatTokenCount(cat.value).padStart(13);
12868
- lines.push(`${labelWithPct}\u2502${bar.padEnd(barWidth)}\u2502${valueStr}`);
12869
- }
12870
- lines.push("");
12871
- lines.push("\u2500".repeat(60));
12872
- lines.push("");
12873
- lines.push("Summary:");
12874
- if (breakdown.prunedTokens > 0) {
12875
- const withoutPruning = breakdown.total + breakdown.prunedTokens;
12876
- const pruned = [];
12877
- if (breakdown.prunedToolCount > 0) pruned.push(`${breakdown.prunedToolCount} tools`);
12878
- if (breakdown.prunedMessageCount > 0)
12879
- pruned.push(`${breakdown.prunedMessageCount} messages`);
12880
- lines.push(
12881
- ` Pruned: ${pruned.join(", ")} (~${formatTokenCount(breakdown.prunedTokens)})`
12882
- );
12883
- lines.push(` Current context: ~${formatTokenCount(breakdown.total)}`);
12884
- lines.push(` Without ACP: ~${formatTokenCount(withoutPruning)}`);
12885
- } else {
12886
- lines.push(` Current context: ~${formatTokenCount(breakdown.total)}`);
12887
- }
12888
- lines.push("");
12889
- return lines.join("\n");
12890
- }
12891
- async function handleContextCommand(ctx) {
12892
- const { client, state, logger, sessionId, messages } = ctx;
12893
- const breakdown = analyzeTokens(state, messages);
12894
- const message = formatContextMessage(breakdown);
12895
- const params = getCurrentParams(state, messages, logger);
12896
- await sendIgnoredMessage(client, sessionId, message, params, logger);
12897
- }
12898
-
12899
- // src/commands/stats.ts
12900
- async function handleStatsCommand(ctx) {
12901
- const report = buildStatusReport(
12902
- { state: ctx.state, config: ctx.config },
12903
- ctx.messages
12904
- );
12905
- const text = `[ACP Status]
12906
- ${report}`;
12907
- await sendIgnoredMessage(
12908
- ctx.client,
12909
- ctx.sessionId,
12910
- text,
12911
- {
12912
- providerId: ctx.userInfo?.providerId,
12913
- modelId: ctx.userInfo?.modelId,
12914
- agent: ctx.userInfo?.agent,
12915
- variant: ctx.userInfo?.variant
12916
- },
12917
- ctx.logger
12918
- );
12919
- }
12920
-
12921
- // src/commands/export.ts
12922
- import * as fs2 from "fs/promises";
12923
- import { existsSync as existsSync7 } from "fs";
12924
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join7, resolve } from "path";
12925
- var ALL_TIERS = [1, 2, 3];
12926
- var TIER_NAMES = {
12927
- 1: "Tier 1 \u2014 Capture",
12928
- 2: "Tier 2 \u2014 Distilled",
12929
- 3: "Tier 3 \u2014 Condensed"
12930
- };
12931
- function parseExportArgs(rawArgs) {
12932
- const options = {
12933
- outputPath: "",
12934
- // "" sentinel => default path resolved later
12935
- tiers: /* @__PURE__ */ new Set(),
12936
- includeMetadata: true,
12937
- append: false
12938
- };
12939
- const tokens = tokenize2(rawArgs);
12940
- let i = 0;
12941
- while (i < tokens.length) {
12942
- const tok = tokens[i];
12943
- const [flag, inlineValue] = splitFlag(tok);
12944
- switch (flag) {
12945
- case "--output":
12946
- case "-o": {
12947
- const value = inlineValue ?? tokens[i + 1];
12948
- if (value === void 0) {
12949
- throw new Error("--output requires a path (use `-` for stdout)");
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;
12950
12904
  }
12951
- options.outputPath = value;
12952
- i += inlineValue !== void 0 ? 1 : 2;
12953
- break;
12954
- }
12955
- case "--tier":
12956
- case "-t": {
12957
- const value = inlineValue ?? tokens[i + 1];
12958
- if (value === void 0) {
12959
- throw new Error("--tier requires a value (e.g. t2,t3 or all)");
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);
12960
12910
  }
12961
- options.tiers = parseTiers(value);
12962
- i += inlineValue !== void 0 ? 1 : 2;
12963
- break;
12964
12911
  }
12965
- case "--no-metadata":
12966
- if (inlineValue !== void 0) {
12967
- throw new Error("--no-metadata does not take a value");
12968
- }
12969
- options.includeMetadata = false;
12970
- i += 1;
12971
- break;
12972
- case "--metadata":
12973
- if (inlineValue !== void 0) {
12974
- throw new Error("--metadata does not take a value");
12975
- }
12976
- options.includeMetadata = true;
12977
- i += 1;
12978
- break;
12979
- case "--append":
12980
- if (inlineValue !== void 0) {
12981
- throw new Error("--append does not take a value");
12982
- }
12983
- options.append = true;
12984
- i += 1;
12985
- break;
12986
- case "--stdout":
12987
- if (inlineValue !== void 0) {
12988
- throw new Error("--stdout does not take a value");
12989
- }
12990
- options.outputPath = "-";
12991
- i += 1;
12992
- break;
12993
- default:
12994
- throw new Error(
12995
- `Unknown flag: ${tok}. Supported: --output, --tier, --no-metadata, --append, --stdout.`
12996
- );
12997
- }
12998
- }
12999
- return options;
13000
- }
13001
- function tokenize2(input) {
13002
- const tokens = [];
13003
- const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
13004
- let m;
13005
- while ((m = re.exec(input)) !== null) {
13006
- tokens.push(m[1] ?? m[2] ?? m[3]);
13007
- }
13008
- return tokens;
13009
- }
13010
- function splitFlag(tok) {
13011
- const eq = tok.indexOf("=");
13012
- if (eq === -1) return [tok, void 0];
13013
- return [tok.slice(0, eq), tok.slice(eq + 1)];
13014
- }
13015
- function parseTiers(raw) {
13016
- const lower = raw.trim().toLowerCase();
13017
- if (lower === "all") return new Set(ALL_TIERS);
13018
- const parts = lower.split(",").map((p) => p.trim()).filter((p) => p.length > 0);
13019
- const result = /* @__PURE__ */ new Set();
13020
- for (const part of parts) {
13021
- const digits = part.replace(/^t/i, "");
13022
- const n = Number(digits);
13023
- if (!Number.isInteger(n) || n < 1 || n > 3) {
13024
- throw new Error(
13025
- `Invalid tier "${part}". Expected t1, t2, t3, a combination (t2,t3), or "all".`
13026
- );
13027
12912
  }
13028
- result.add(n);
13029
12913
  }
13030
- if (result.size === 0) {
13031
- throw new Error(`Invalid tier "${raw}". Expected t1, t2, t3, or "all".`);
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
+ });
13032
12921
  }
13033
12922
  return result;
13034
12923
  }
13035
- function resolveDefaultOutputPath(sessionId, cwd2) {
13036
- const short = (sessionId || "session").slice(0, 8);
13037
- return join7(cwd2, ".opencode", `acp-export-${short}.md`);
13038
- }
13039
- function formatTokens2(n) {
13040
- if (!Number.isFinite(n) || n <= 0) return "0";
13041
- return n >= 1e3 ? `${(n / 1e3).toFixed(1)}K` : String(n);
13042
- }
13043
- function effectiveTokens(block) {
13044
- return block.effectiveCompressedTokens ?? block.compressedTokens ?? 0;
13045
- }
13046
- function collectActiveBlocks(state) {
13047
- const msgState = state.prune.messages;
13048
- const blocks = [];
13049
- for (const id of msgState.activeBlockIds) {
13050
- const block = msgState.blocksById.get(id);
13051
- if (block && block.active) {
13052
- blocks.push(block);
13053
- }
13054
- }
13055
- return blocks;
13056
- }
13057
- function filterByTier(blocks, tiers) {
13058
- if (tiers.size === 0) return blocks;
13059
- return blocks.filter((b) => tiers.has(b.tier ?? 1));
13060
- }
13061
- function tokenSpans(blocks) {
13062
- return {
13063
- effective: blocks.reduce((s, b) => s + effectiveTokens(b), 0),
13064
- summary: blocks.reduce((s, b) => s + (b.summaryTokens || 0), 0)
13065
- };
13066
- }
13067
- function tierCounts(blocks) {
13068
- const counts = {};
13069
- for (const b of blocks) {
13070
- const t = b.tier ?? 1;
13071
- counts[t] = (counts[t] || 0) + 1;
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" };
12941
+ }
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)` };
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
+ };
13072
12962
  }
13073
- return ALL_TIERS.filter((t) => counts[t]).map((t) => `T${t}: ${counts[t]}`).join(", ");
13074
- }
13075
- function renderExportMarkdown(params) {
13076
- const { sessionId, generatedAt, blocks, tiers, includeMetadata } = params;
13077
- const out = [];
13078
- const tierFilterLabel = tiers.size === 0 ? "all" : ALL_TIERS.filter((t) => tiers.has(t)).map((t) => `T${t}`).join(", ");
13079
- out.push("# ACP Session Export");
13080
- out.push("");
13081
- out.push(`- **Session**: \`${(sessionId || "unknown").slice(0, 16)}\``);
13082
- out.push(`- **Generated**: ${generatedAt.toISOString()}`);
13083
- out.push(`- **Blocks exported**: ${blocks.length}`);
13084
- const breakdown = tierCounts(blocks);
13085
- if (breakdown) {
13086
- out.push(` - ${breakdown}`);
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" };
12977
+ }
12978
+ return { action: "drop", reason: "TODO CONTINUATION directive" };
13087
12979
  }
13088
- out.push(`- **Tiers**: ${tierFilterLabel}`);
13089
- const span = tokenSpans(blocks);
13090
- if (blocks.length > 0) {
13091
- out.push(
13092
- `- **Coverage**: ${formatTokens2(span.effective)} original \u2192 ${formatTokens2(span.summary)} summary`
13093
- );
12980
+ };
12981
+
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" };
13094
12997
  }
13095
- out.push("");
13096
- out.push("---");
13097
- out.push("");
13098
- if (blocks.length === 0) {
13099
- out.push("_No active compression blocks match the selected tiers._");
13100
- out.push("");
13101
- out.push(
13102
- "Tip: run `/acp export --tier all` to include every active tier, or trigger a compression first."
13103
- );
13104
- return out.join("\n");
12998
+ };
12999
+
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" };
13105
13015
  }
13106
- for (const tier of [3, 2, 1]) {
13107
- const tierBlocks = blocks.filter((b) => (b.tier ?? 1) === tier).sort((a, b) => a.blockId - b.blockId);
13108
- if (tierBlocks.length === 0) continue;
13109
- out.push(`## ${TIER_NAMES[tier]}`);
13110
- out.push("");
13111
- for (const block of tierBlocks) {
13112
- const topic = block.topic || block.batchTopic || "(no topic)";
13113
- out.push(`### b${block.blockId} \u2014 ${topic}`);
13114
- out.push("");
13115
- if (includeMetadata) {
13116
- const mode = block.mode ?? "range";
13117
- const msgCount = block.effectiveMessageIds?.length ?? 0;
13118
- const created = new Date(block.createdAt).toISOString();
13119
- const age = block.survivedCount ?? 0;
13120
- out.push(`- **Tier**: T${tier} \xB7 **Mode**: ${mode}`);
13121
- out.push(`- **Messages**: ${msgCount} (effective)`);
13122
- out.push(
13123
- `- **Tokens**: ${formatTokens2(effectiveTokens(block))} \u2192 ${formatTokens2(block.summaryTokens || 0)} summary`
13124
- );
13125
- out.push(`- **Created**: ${created}`);
13126
- out.push(`- **Age**: survived ${age} transform${age === 1 ? "" : "s"}`);
13127
- out.push("");
13016
+ };
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);
13037
+ }
13038
+ matched = true;
13039
+ break;
13128
13040
  }
13129
- const summary = (block.summary || "").trim() || "_(empty summary)_";
13130
- out.push(summary);
13131
- out.push("");
13132
- out.push("---");
13133
- out.push("");
13134
13041
  }
13135
- }
13136
- return out.join("\n");
13137
- }
13138
- async function handleExportCommand(ctx, args) {
13139
- const { client, state, logger, sessionId } = ctx;
13140
- let options;
13141
- try {
13142
- options = parseExportArgs(args);
13143
- } catch (err) {
13144
- const msg = err?.message ?? String(err);
13145
- logger.warn("export: argument parse failed", { error: msg, args });
13146
- await sendExportNotice(client, sessionId, ctx, `[ACP Export] ${msg}`);
13147
- return;
13148
- }
13149
- const tiers = options.tiers;
13150
- const allActive = collectActiveBlocks(state);
13151
- const blocks = filterByTier(allActive, tiers);
13152
- const generatedAt = /* @__PURE__ */ new Date();
13153
- const markdown = renderExportMarkdown({
13154
- sessionId,
13155
- generatedAt,
13156
- blocks,
13157
- tiers,
13158
- includeMetadata: options.includeMetadata
13159
- });
13160
- if (options.outputPath === "-") {
13161
- await sendExportNotice(client, sessionId, ctx, markdown);
13162
- return;
13163
- }
13164
- const cwd2 = ctx.workingDirectory || process.cwd();
13165
- const targetPath = options.outputPath !== "" ? isAbsolute2(options.outputPath) ? options.outputPath : resolve(cwd2, options.outputPath) : resolveDefaultOutputPath(sessionId, cwd2);
13166
- try {
13167
- const dir = dirname3(targetPath);
13168
- if (!existsSync7(dir)) {
13169
- await fs2.mkdir(dir, { recursive: true });
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
+ }
13170
13050
  }
13171
- const flag = options.append ? "a" : "w";
13172
- if (options.append && existsSync7(targetPath)) {
13173
- await fs2.appendFile(targetPath, `
13174
-
13175
- ---
13176
-
13177
- ${markdown}`, "utf-8");
13051
+ if (matched) {
13052
+ strippedAny = true;
13178
13053
  } else {
13179
- await fs2.writeFile(targetPath, markdown, { flag, encoding: "utf-8" });
13054
+ break;
13180
13055
  }
13181
- } catch (err) {
13182
- const msg = err?.message ?? String(err);
13183
- logger.warn("export: file write failed", { path: targetPath, error: msg });
13184
- await sendExportNotice(
13185
- client,
13186
- sessionId,
13187
- ctx,
13188
- `[ACP Export] Failed to write \`${targetPath}\`: ${msg}`
13189
- );
13190
- return;
13191
13056
  }
13192
- logger.info("export: wrote markdown", {
13193
- path: targetPath,
13194
- blocks: blocks.length,
13195
- tiers: tiers.size ? [...tiers].sort().join(",") : "all"
13196
- });
13197
- const summary = formatExportSummary(targetPath, blocks, allActive, generatedAt);
13198
- await sendExportNotice(client, sessionId, ctx, summary);
13057
+ return strippedAny ? current.trim() : null;
13199
13058
  }
13200
- function formatExportSummary(path, exported, allActive, generatedAt) {
13201
- const lines = [];
13202
- lines.push("[ACP Export]");
13203
- lines.push(`Wrote ${exported.length} block${exported.length === 1 ? "" : "s"} to:`);
13204
- lines.push(` ${path}`);
13205
- if (exported.length === 0) {
13206
- lines.push("");
13207
- lines.push(
13208
- `No matching blocks (of ${allActive.length} active). Try \`/acp export --tier all\`.`
13209
- );
13210
- } else {
13211
- lines.push("");
13212
- lines.push(`Generated ${generatedAt.toISOString()}.`);
13213
- lines.push(
13214
- "Review, edit, and commit as project notes \u2014 export is user-driven, never auto-injected."
13215
- );
13216
- }
13217
- return lines.join("\n");
13218
- }
13219
- async function sendExportNotice(client, sessionId, ctx, text) {
13220
- await sendIgnoredMessage(client, sessionId, text, {}, ctx.logger);
13221
- }
13222
-
13223
- // src/messages/filter/registry.ts
13224
- var registry3 = /* @__PURE__ */ new Map();
13225
- function registerMessageFilter(filter) {
13226
- const existing = registry3.get(filter.name);
13227
- if (existing && existing.version !== filter.version) {
13228
- throw new Error(
13229
- `Message filter "${filter.name}" already registered with version ${existing.version}, cannot register version ${filter.version}. Use a different name or bump version.`
13230
- );
13231
- }
13232
- registry3.set(filter.name, filter);
13233
- }
13234
- function getMessageFilter(name) {
13235
- return registry3.get(name);
13236
- }
13237
- function listMessageFilters() {
13238
- return Array.from(registry3.values());
13239
- }
13240
-
13241
- // src/messages/filter/apply.ts
13242
- function applyMessageFilters(messages, config, logger, ctx) {
13243
- if (!config?.enabled) {
13244
- return { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
13245
- }
13246
- const allFilters = listMessageFilters().filter((f) => {
13247
- const fc = config.filters?.[f.name];
13248
- return fc?.enabled !== false;
13249
- });
13250
- if (allFilters.length === 0) {
13251
- return { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
13252
- }
13253
- const result = { partsFiltered: 0, partsDropped: 0, partsModified: 0 };
13254
- const total = messages.length;
13255
- const warnedFilters = /* @__PURE__ */ new Set();
13256
- const buildCtx = (text, role, i) => ({
13257
- text,
13258
- role,
13259
- sessionId: ctx.sessionId,
13260
- isSubAgent: ctx.isSubAgent,
13261
- messageIndex: i,
13262
- totalMessages: total,
13263
- modelContextLimit: ctx.modelContextLimit
13264
- });
13265
- const applyDecision = (part, decision, filterName, i, originalText) => {
13266
- result.partsFiltered++;
13267
- if (decision.action === "drop") {
13268
- part.text = "";
13269
- result.partsDropped++;
13270
- if (decision.reason) {
13271
- logger.debug("Message filter dropped text", {
13272
- filter: filterName,
13273
- reason: decision.reason,
13274
- messageIndex: i,
13275
- originalLength: originalText.length
13276
- });
13277
- }
13278
- return "";
13279
- }
13280
- if (decision.action === "modify" && decision.text !== void 0) {
13281
- part.text = decision.text;
13282
- result.partsModified++;
13283
- if (decision.reason) {
13284
- logger.debug("Message filter modified text", {
13285
- filter: filterName,
13286
- reason: decision.reason,
13287
- messageIndex: i,
13288
- originalLength: originalText.length,
13289
- newLength: decision.text.length
13290
- });
13291
- }
13292
- return decision.text;
13293
- }
13294
- return originalText;
13295
- };
13296
- const immediateFilters = allFilters.filter((f) => !f.keepLastOnly);
13297
- for (let i = 0; i < messages.length; i++) {
13298
- const msg = messages[i];
13299
- const role = msg.info.role ?? "unknown";
13300
- for (const part of msg.parts ?? []) {
13301
- const text = part.text;
13302
- if (typeof text !== "string" || text.length === 0) continue;
13303
- let current = text;
13304
- const filterCtx = buildCtx(current, role, i);
13305
- filterCtx.toolName = part.tool;
13306
- for (const filter of immediateFilters) {
13307
- let decision;
13308
- try {
13309
- decision = filter.filter(filterCtx);
13310
- } catch (err) {
13311
- if (!warnedFilters.has(filter.name)) {
13312
- warnedFilters.add(filter.name);
13313
- logger.warn("Message filter threw error", {
13314
- filter: filter.name,
13315
- error: err instanceof Error ? err.message : String(err),
13316
- messageIndex: i
13317
- });
13318
- }
13319
- continue;
13320
- }
13321
- if (decision.action === "keep") continue;
13322
- current = applyDecision(part, decision, filter.name, i, current);
13323
- filterCtx.text = current;
13324
- }
13325
- }
13326
- }
13327
- const keepLastFilters = allFilters.filter((f) => f.keepLastOnly);
13328
- for (const filter of keepLastFilters) {
13329
- const fcKeepLast = config.filters?.[filter.name]?.keepLast;
13330
- const keepCount = Math.max(1, fcKeepLast ?? filter.keepLast ?? 1);
13331
- let kept = 0;
13332
- for (let i = messages.length - 1; i >= 0; i--) {
13333
- const msg = messages[i];
13334
- const role = msg.info.role ?? "unknown";
13335
- const parts = msg.parts ?? [];
13336
- for (let p = parts.length - 1; p >= 0; p--) {
13337
- const part = parts[p];
13338
- const text = part.text;
13339
- if (typeof text !== "string" || text.length === 0) continue;
13340
- const filterCtx = buildCtx(text, role, i);
13341
- filterCtx.toolName = part.tool;
13342
- let decision;
13343
- try {
13344
- decision = filter.filter(filterCtx);
13345
- } catch {
13346
- continue;
13347
- }
13348
- if (decision.action !== "drop" && decision.action !== "modify") continue;
13349
- if (kept < keepCount) {
13350
- kept++;
13351
- } else {
13352
- applyDecision(part, decision, filter.name, i, text);
13353
- }
13354
- }
13355
- }
13356
- }
13357
- if (result.partsFiltered > 0) {
13358
- logger.info("Message filters applied", {
13359
- filtersRun: allFilters.length,
13360
- partsFiltered: result.partsFiltered,
13361
- partsDropped: result.partsDropped,
13362
- partsModified: result.partsModified
13363
- });
13364
- }
13365
- return result;
13366
- }
13367
-
13368
- // src/messages/filter/builtin/omo-system-reminder.ts
13369
- var SYSTEM_REMINDER_OPEN = "<system-reminder>";
13370
- var OMO_MARKER = "<!-- OMO_INTERNAL_INITIATOR -->";
13371
- var PAIRED_BLOCK_RE = /<system-reminder>[\s\S]*?<\/system-reminder>\s*<!-- OMO_INTERNAL_INITIATOR -->/g;
13372
- var LONE_REMINDER_RE = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
13373
- var LONE_MARKER_RE = /<!-- OMO_INTERNAL_INITIATOR -->/g;
13374
- var OMO_SYSTEM_REMINDER_FILTER = {
13375
- name: "omo-system-reminder",
13376
- version: "1.3.0",
13377
- description: "Keep recent OMO <system-reminder> messages; for older ones, strip blocks but preserve user content",
13378
- keepLastOnly: true,
13379
- keepLast: 2,
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",
13380
13063
  filter(ctx) {
13381
13064
  if (ctx.role !== "user") return { action: "keep" };
13382
- if (!ctx.text.includes(SYSTEM_REMINDER_OPEN) && !ctx.text.includes(OMO_MARKER)) {
13383
- return { action: "keep" };
13384
- }
13385
- let modified = ctx.text;
13386
- let removedBlocks = 0;
13387
- modified = modified.replace(PAIRED_BLOCK_RE, () => {
13388
- removedBlocks++;
13389
- return "";
13390
- });
13391
- modified = modified.replace(LONE_REMINDER_RE, () => {
13392
- removedBlocks++;
13393
- return "";
13394
- });
13395
- modified = modified.replace(LONE_MARKER_RE, "");
13396
- modified = modified.replace(/\n{3,}/g, "\n\n").trim();
13397
- if (modified.length === 0) {
13398
- return { action: "drop", reason: `Pure OMO system-reminder (${removedBlocks} block(s), no user content)` };
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)" };
13399
13069
  }
13400
13070
  return {
13401
13071
  action: "modify",
13402
- text: modified,
13403
- reason: `Stripped ${removedBlocks} OMO system-reminder block(s), preserved user content (${modified.length} chars)`
13072
+ text: remaining,
13073
+ reason: "Stripped OMO mode injection block(s), preserved user content"
13404
13074
  };
13405
13075
  }
13406
13076
  };
13407
13077
 
13408
- // src/messages/filter/builtin/omo-todo-continuation.ts
13409
- var TODO_MARKER = "[SYSTEM DIRECTIVE";
13410
- var TODO_CONTINUATION = "TODO CONTINUATION";
13411
- var OMO_TODO_FILTER = {
13412
- name: "omo-todo-continuation",
13413
- version: "1.0.0",
13414
- description: "Keep only the latest OMO TODO CONTINUATION directive, drop earlier occurrences",
13415
- keepLastOnly: true,
13416
- filter(ctx) {
13417
- if (ctx.role !== "user") return { action: "keep" };
13418
- if (!ctx.text.includes(TODO_MARKER) || !ctx.text.includes(TODO_CONTINUATION)) {
13419
- return { action: "keep" };
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);
13420
13090
  }
13421
- return { action: "drop", reason: "TODO CONTINUATION directive" };
13422
13091
  }
13423
- };
13092
+ }
13424
13093
 
13425
- // src/messages/filter/builtin/omo-context.ts
13426
- var OMO_MARKER2 = "<!-- OMO_INTERNAL_INITIATOR -->";
13427
- var OMO_CONTEXT_FILTER = {
13428
- name: "omo-context",
13429
- version: "1.0.0",
13430
- description: "Keep only the latest OMO [CONTEXT] injection, drop earlier occurrences",
13431
- keepLastOnly: true,
13432
- filter(ctx) {
13433
- if (ctx.role !== "user") return { action: "keep" };
13434
- if (!ctx.text.includes(OMO_MARKER2)) return { action: "keep" };
13435
- const stripped = ctx.text.trimStart();
13436
- if (!stripped.startsWith("[CONTEXT]") && !stripped.startsWith("CONTEXT:")) {
13437
- return { action: "keep" };
13438
- }
13439
- return { action: "drop", reason: "OMO context injection" };
13440
- }
13441
- };
13442
-
13443
- // src/messages/filter/builtin/omo-task-directive.ts
13444
- var OMO_MARKER3 = "<!-- OMO_INTERNAL_INITIATOR -->";
13445
- var OMO_TASK_FILTER = {
13446
- name: "omo-task-directive",
13447
- version: "1.0.0",
13448
- description: "Keep only the latest OMO TASK directive, drop earlier occurrences",
13449
- keepLastOnly: true,
13450
- filter(ctx) {
13451
- if (ctx.role !== "user") return { action: "keep" };
13452
- if (!ctx.text.includes(OMO_MARKER3)) return { action: "keep" };
13453
- const stripped = ctx.text.trimStart();
13454
- if (!stripped.startsWith("TASK:") && !stripped.startsWith("## TASK")) {
13455
- return { action: "keep" };
13456
- }
13457
- return { action: "drop", reason: "OMO task directive" };
13458
- }
13459
- };
13460
-
13461
- // src/messages/filter/builtin/omo-mode-injection.ts
13462
- var XML_MODE_TAGS = [
13463
- { open: "<hyperplan-ultrawork-mode>", close: "</hyperplan-ultrawork-mode>" },
13464
- { open: "<ultrawork-mode>", close: "</ultrawork-mode>" }
13465
- ];
13466
- var BRACKET_MODE_PATTERNS = ["[search-mode]", "[analyze-mode]", "[ultrawork-mode]"];
13467
- function stripLeadingModeInjections(text) {
13468
- let current = text;
13469
- let strippedAny = false;
13470
- for (let iter = 0; iter < 5; iter++) {
13471
- current = current.trimStart();
13472
- let matched = false;
13473
- for (const { open, close } of XML_MODE_TAGS) {
13474
- if (current.startsWith(open)) {
13475
- const closeIdx = current.indexOf(close);
13476
- if (closeIdx !== -1) {
13477
- current = current.slice(closeIdx + close.length);
13478
- } else {
13479
- current = current.slice(open.length);
13480
- }
13481
- matched = true;
13482
- break;
13483
- }
13484
- }
13485
- if (!matched) {
13486
- for (const pattern of BRACKET_MODE_PATTERNS) {
13487
- if (current.startsWith(pattern)) {
13488
- current = current.slice(pattern.length);
13489
- matched = true;
13490
- break;
13491
- }
13492
- }
13493
- }
13494
- if (matched) {
13495
- strippedAny = true;
13496
- } else {
13497
- break;
13498
- }
13499
- }
13500
- return strippedAny ? current.trim() : null;
13501
- }
13502
- var OMO_MODE_FILTER = {
13503
- name: "omo-mode-injection",
13504
- version: "1.1.0",
13505
- description: "Strip OMO mode injection blocks (<ultrawork-mode>...</ultrawork-mode>, [search-mode], etc.) from user messages, preserving user content",
13506
- filter(ctx) {
13507
- if (ctx.role !== "user") return { action: "keep" };
13508
- const remaining = stripLeadingModeInjections(ctx.text);
13509
- if (remaining === null) return { action: "keep" };
13510
- if (remaining.length === 0) {
13511
- return { action: "drop", reason: "OMO mode injection (no user content after stripping)" };
13512
- }
13513
- return {
13514
- action: "modify",
13515
- text: remaining,
13516
- reason: "Stripped OMO mode injection block(s), preserved user content"
13517
- };
13518
- }
13519
- };
13520
-
13521
- // src/messages/filter/builtin/index.ts
13522
- var BUILTIN_FILTERS = [
13523
- OMO_SYSTEM_REMINDER_FILTER,
13524
- OMO_TODO_FILTER,
13525
- OMO_CONTEXT_FILTER,
13526
- OMO_TASK_FILTER,
13527
- OMO_MODE_FILTER
13528
- ];
13529
- function ensureBuiltinFiltersRegistered() {
13530
- for (const filter of BUILTIN_FILTERS) {
13531
- if (!getMessageFilter(filter.name)) {
13532
- registerMessageFilter(filter);
13533
- }
13534
- }
13535
- }
13536
-
13537
- // src/gc/merge.ts
13538
- function collectActiveOldGenBlocks(state, maxOldGenSummaryLength) {
13539
- const blocks = [];
13540
- const ids = Array.from(state.prune.messages.activeBlockIds).sort((a, b) => a - b);
13541
- for (const id of ids) {
13542
- const block = state.prune.messages.blocksById.get(id);
13543
- if (!block || !block.active) continue;
13544
- if (block.generation === "old" || block.generation === void 0 || block.summary.length > maxOldGenSummaryLength) {
13545
- blocks.push(block);
13094
+ // src/gc/merge.ts
13095
+ function collectActiveOldGenBlocks(state, maxOldGenSummaryLength) {
13096
+ const blocks = [];
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) {
13102
+ blocks.push(block);
13546
13103
  }
13547
13104
  }
13548
13105
  return blocks;
@@ -13708,13 +13265,7 @@ function runBatchCleanup(state, config, logger, messages) {
13708
13265
  };
13709
13266
  }
13710
13267
 
13711
- // src/hooks.ts
13712
- var INTERNAL_AGENT_SIGNATURES = [
13713
- "You are a title generator",
13714
- "You are a helpful AI assistant tasked with summarizing conversations",
13715
- "You are an anchored context summarization assistant for coding sessions",
13716
- "Summarize what was done in this conversation"
13717
- ];
13268
+ // src/hooks/messages.ts
13718
13269
  var INTERNAL_AGENT_NAMES = /* @__PURE__ */ new Set(["title", "summary", "compaction"]);
13719
13270
  function isInternalAgentRequest(messages) {
13720
13271
  const lastUserMessage = getLastUserMessage(messages);
@@ -13724,57 +13275,6 @@ function isInternalAgentRequest(messages) {
13724
13275
  const agent = lastUserMessage.info.agent;
13725
13276
  return typeof agent === "string" && INTERNAL_AGENT_NAMES.has(agent);
13726
13277
  }
13727
- function createSystemPromptHandler(registry4, logger, config, prompts) {
13728
- return async (input, output) => {
13729
- registry4.recordModelLimit(
13730
- input.model?.providerID,
13731
- input.model?.id,
13732
- input.model?.limit?.context
13733
- );
13734
- const state = input.sessionID ? registry4.get(input.sessionID) : void 0;
13735
- if (!state || state.isSubAgent && !config.allowSubAgents) {
13736
- return;
13737
- }
13738
- const systemText = output.system.join("\n");
13739
- if (INTERNAL_AGENT_SIGNATURES.some((sig) => systemText.includes(sig))) {
13740
- logger.info("Skipping ACP system prompt injection for internal agent");
13741
- return;
13742
- }
13743
- if (input.model?.limit?.context) {
13744
- const limit = input.model.limit.context;
13745
- const providerID = input.model?.providerID;
13746
- const modelID = input.model?.id;
13747
- const changed = state.modelContextLimit !== limit || providerID !== void 0 && state.modelProviderID !== providerID || modelID !== void 0 && state.modelID !== modelID;
13748
- state.modelContextLimit = limit;
13749
- if (providerID !== void 0) {
13750
- state.modelProviderID = providerID;
13751
- }
13752
- if (modelID !== void 0) {
13753
- state.modelID = modelID;
13754
- }
13755
- if (changed) {
13756
- saveSessionState(state, logger).catch(() => {
13757
- });
13758
- }
13759
- }
13760
- const effectivePermission = compressPermission(state, config);
13761
- if (effectivePermission === "deny") {
13762
- return;
13763
- }
13764
- prompts.reload();
13765
- const runtimePrompts = prompts.getRuntimePrompts();
13766
- const newPrompt = renderSystemPrompt(
13767
- runtimePrompts,
13768
- buildProtectedToolsExtension(config.compress.protectedTools),
13769
- state.isSubAgent && config.allowSubAgents
13770
- );
13771
- if (output.system.length > 0) {
13772
- output.system[output.system.length - 1] += "\n\n" + newPrompt;
13773
- } else {
13774
- output.system.push(newPrompt);
13775
- }
13776
- };
13777
- }
13778
13278
  function createChatMessageTransformHandler(client, registry4, logger, config, prompts, hostPermissions) {
13779
13279
  return async (input, output) => {
13780
13280
  const diagnostic = currentDiagnostic();
@@ -14016,34 +13516,538 @@ ${text}`);
14016
13516
  }
14017
13517
  );
14018
13518
  }
14019
- }
14020
- logger.info("Chat transform complete", {
14021
- session: state.sessionId,
14022
- model: state.modelID,
14023
- messages: output.messages.length,
14024
- prePruneTokens,
14025
- postTokens,
14026
- contextLimit: effectiveLimit?.limit,
14027
- contextLimitSource: effectiveLimit?.source,
14028
- usagePct: postTokens !== void 0 && effectiveLimit ? `${(postTokens / effectiveLimit.limit * 100).toFixed(1)}%` : void 0,
14029
- nudged: state.nudges.shouldInjectThisTurn
14030
- });
14031
- checkpoint("saveContext");
14032
- if (diagnostic) {
14033
- diagnostic.counts.blocks = state.prune.messages.blocksById.size;
14034
- diagnostic.counts.activeBlocks = state.prune.messages.activeBlockIds.size;
14035
- }
14036
- if (state.sessionId) {
14037
- await logger.saveContext(state.sessionId, output.messages);
14038
- }
14039
- } catch (error) {
14040
- diagnostic?.fail("transform");
14041
- throw error;
14042
- } finally {
14043
- timeline?.end();
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();
13544
+ }
13545
+ };
13546
+ }
13547
+
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
+ }
13570
+ }
13571
+ }
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
+ }
13581
+ }
13582
+ }
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
+ }
13616
+ }
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;
13633
+ }
13634
+ }
13635
+ }
13636
+ if (msg.info.role === "user" && !isIgnoredUser && !foundFirstUser) {
13637
+ foundFirstUser = true;
13638
+ }
13639
+ }
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++;
13645
+ }
13646
+ }
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)}`);
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);
13724
+ }
13725
+
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
+ );
13824
+ }
13825
+ }
13826
+ return options;
13827
+ }
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]);
13834
+ }
13835
+ return tokens;
13836
+ }
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)];
13841
+ }
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
+ );
13854
+ }
13855
+ result.add(n);
13856
+ }
13857
+ if (result.size === 0) {
13858
+ throw new Error(`Invalid tier "${raw}". Expected t1, t2, t3, or "all".`);
13859
+ }
13860
+ return result;
13861
+ }
13862
+ function resolveDefaultOutputPath(sessionId, cwd2) {
13863
+ const short = (sessionId || "session").slice(0, 8);
13864
+ return join7(cwd2, ".opencode", `acp-export-${short}.md`);
13865
+ }
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);
14044
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)
14045
13892
  };
14046
13893
  }
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`
13951
+ );
13952
+ out.push(`- **Created**: ${created}`);
13953
+ out.push(`- **Age**: survived ${age} transform${age === 1 ? "" : "s"}`);
13954
+ out.push("");
13955
+ }
13956
+ const summary = (block.summary || "").trim() || "_(empty summary)_";
13957
+ out.push(summary);
13958
+ out.push("");
13959
+ out.push("---");
13960
+ out.push("");
13961
+ }
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 });
13997
+ }
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" });
14007
+ }
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}`
14016
+ );
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);
14048
+ }
14049
+
14050
+ // src/hooks/command.ts
14047
14051
  function buildHelpText() {
14048
14052
  return [
14049
14053
  "[ACP] Available commands:",
@@ -14093,6 +14097,8 @@ function createCommandExecuteHandler(client, registry4, logger, config, workingD
14093
14097
  }
14094
14098
  };
14095
14099
  }
14100
+
14101
+ // src/hooks/event.ts
14096
14102
  function createEventHandler(registry4, logger) {
14097
14103
  return async (input) => {
14098
14104
  if (input.event?.type === "session.idle" || input.event?.type === "session.deleted") {