@infituit/opencode-acp 2.0.0-alpha.7 → 2.0.0-alpha.8

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
@@ -2243,6 +2243,15 @@ function isSyntheticMessage(message) {
2243
2243
  const id = message?.info?.id;
2244
2244
  return typeof id === "string" && (id.startsWith("msg_acp_summary_") || id.startsWith("msg_acp_text_") || id.startsWith("msg_acp_recap_"));
2245
2245
  }
2246
+ function isHostInput(message) {
2247
+ return isMessageWithInfo(message) && message.info.role === "user" && message.info.hostInput !== void 0;
2248
+ }
2249
+ function isUserPrompt(message) {
2250
+ return isMessageWithInfo(message) && message.info.role === "user" && !isHostInput(message) && !isIgnoredUserMessage(message) && !isSyntheticMessage(message);
2251
+ }
2252
+ function getRequestInput(messages) {
2253
+ return getLastUserMessage(messages) ?? messages.findLast(isHostInput) ?? null;
2254
+ }
2246
2255
  var getLastUserMessage = (messages, startIndex) => {
2247
2256
  const start = startIndex ?? messages.length - 1;
2248
2257
  for (let i = start; i >= 0; i--) {
@@ -2250,7 +2259,7 @@ var getLastUserMessage = (messages, startIndex) => {
2250
2259
  if (!isMessageWithInfo(msg)) {
2251
2260
  continue;
2252
2261
  }
2253
- if (msg.info.role === "user" && !isIgnoredUserMessage(msg) && !isSyntheticMessage(msg)) {
2262
+ if (isUserPrompt(msg)) {
2254
2263
  return msg;
2255
2264
  }
2256
2265
  }
@@ -2398,7 +2407,7 @@ function estimateSystemPromptTokens(messages) {
2398
2407
  if (firstInput === void 0) return 0;
2399
2408
  let firstUserText = "";
2400
2409
  for (const msg of messages) {
2401
- if (msg.info.role !== "user") continue;
2410
+ if (!isUserPrompt(msg)) continue;
2402
2411
  const parts = Array.isArray(msg.parts) ? msg.parts : [];
2403
2412
  for (const part of parts) {
2404
2413
  if (part.type === "text" && typeof part.text === "string") {
@@ -2410,7 +2419,7 @@ function estimateSystemPromptTokens(messages) {
2410
2419
  return Math.max(0, firstInput - countTokens(firstUserText));
2411
2420
  }
2412
2421
  function getCurrentParams(state, messages, logger) {
2413
- const userMsg = getLastUserMessage(messages);
2422
+ const userMsg = getRequestInput(messages);
2414
2423
  if (!userMsg) {
2415
2424
  logger.debug("No user message found when determining current params");
2416
2425
  return {
@@ -2751,7 +2760,7 @@ function collectTurnNudgeAnchors(messages) {
2751
2760
  break;
2752
2761
  }
2753
2762
  if (message.info.role === "user") {
2754
- if (!isIgnoredUserMessage(message)) {
2763
+ if (isUserPrompt(message)) {
2755
2764
  pendingUserMessageId = message.info.id;
2756
2765
  }
2757
2766
  continue;
@@ -3174,7 +3183,7 @@ function assignMessageRefs(state, messages) {
3174
3183
  if (isIgnoredUserMessage(message)) {
3175
3184
  continue;
3176
3185
  }
3177
- if (state.isSubAgent && !skippedSubAgentPrompt && message.info.role === "user") {
3186
+ if (state.isSubAgent && !skippedSubAgentPrompt && isUserPrompt(message)) {
3178
3187
  skippedSubAgentPrompt = true;
3179
3188
  continue;
3180
3189
  }
@@ -3208,6 +3217,7 @@ function repairNonMonotonicMessageRefs(state, messages) {
3208
3217
  let previous = 0;
3209
3218
  let corrupted = false;
3210
3219
  for (const message of eligible) {
3220
+ if (isHostInput(message)) continue;
3211
3221
  const ref = state.messageIds.byRawId.get(message.info.id);
3212
3222
  const parsed = ref ? parseMessageRef(ref) : null;
3213
3223
  if (parsed === null) continue;
@@ -3626,12 +3636,13 @@ function convertToolPart(part) {
3626
3636
  state: {
3627
3637
  status,
3628
3638
  input: state?.input ?? part.input,
3629
- output: textFromContent(output)
3639
+ output: textFromContent(output),
3640
+ ...state?.metadata?.acpHostInputRefs === true ? { metadata: { acpHostInputRefs: true } } : {}
3630
3641
  }
3631
3642
  };
3632
3643
  }
3633
3644
  function convertParts(message) {
3634
- if (message.type === "user") {
3645
+ if (message.type === "user" || message.type === "synthetic") {
3635
3646
  const parts2 = [];
3636
3647
  if (typeof message.text === "string") {
3637
3648
  parts2.push({ type: "text", text: message.text });
@@ -3657,19 +3668,35 @@ function convertParts(message) {
3657
3668
  }
3658
3669
  return parts;
3659
3670
  }
3660
- function fromV2SessionMessages(input, sessionID) {
3671
+ function isAcpNotification(message) {
3672
+ return message.metadata?.source === "opencode-acp" || message.metadata?.source === void 0 && (message.description === "ACP" || message.description === "ACP update ready" || message.description?.startsWith("ACP:") === true);
3673
+ }
3674
+ function fromV2SessionMessages(input, sessionID, requestMessages) {
3661
3675
  if (!Array.isArray(input)) return [];
3676
+ const requestInputs = /* @__PURE__ */ new Map();
3677
+ for (const value of requestMessages ?? []) {
3678
+ if (!value || typeof value !== "object") continue;
3679
+ const message = value;
3680
+ if (message.role === "user" && typeof message.id === "string") {
3681
+ requestInputs.set(message.id, message);
3682
+ }
3683
+ }
3662
3684
  const result = [];
3663
3685
  for (const value of input) {
3664
3686
  if (!value || typeof value !== "object") continue;
3665
3687
  const message = value;
3666
- if (message.type !== "user" && message.type !== "assistant") continue;
3688
+ const hostInput = message.type === "synthetic";
3689
+ if (!hostInput && message.type !== "user" && message.type !== "assistant") continue;
3667
3690
  if (typeof message.id !== "string") continue;
3668
- const role = message.type;
3691
+ const requestInput = requestInputs.get(message.id);
3692
+ if (hostInput && (isAcpNotification(message) || requestMessages && !requestInput))
3693
+ continue;
3694
+ const role = hostInput ? "user" : message.type;
3669
3695
  const info = {
3670
3696
  id: message.id,
3671
3697
  sessionID,
3672
3698
  role,
3699
+ ...hostInput ? { hostInput: { metadata: requestInput?.metadata ?? message.metadata } } : {},
3673
3700
  time: { created: createdAt(message) },
3674
3701
  agent: message.agent ?? "code",
3675
3702
  model: {
@@ -3684,19 +3711,25 @@ function fromV2SessionMessages(input, sessionID) {
3684
3711
  cost: 0,
3685
3712
  tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }
3686
3713
  };
3714
+ const projectedContent = hostInput ? requestInput?.content : void 0;
3715
+ const parts = typeof projectedContent === "string" ? [{ type: "text", text: projectedContent }] : Array.isArray(projectedContent) ? projectedContent.map((part) => structuredClone(part)) : convertParts(message);
3687
3716
  result.push({
3688
3717
  info,
3689
- parts: convertParts(message)
3718
+ parts
3690
3719
  });
3691
3720
  }
3692
3721
  return result;
3693
3722
  }
3694
- async function fetchV2SessionMessages(client, sessionID) {
3723
+ async function fetchV2SessionMessages(client, sessionID, requestMessages) {
3695
3724
  const runtime = client;
3696
3725
  if (typeof runtime.session?.context !== "function") {
3697
3726
  return [];
3698
3727
  }
3699
- return fromV2SessionMessages(await runtime.session.context({ sessionID }), sessionID);
3728
+ return fromV2SessionMessages(
3729
+ await runtime.session.context({ sessionID }),
3730
+ sessionID,
3731
+ requestMessages
3732
+ );
3700
3733
  }
3701
3734
  function toolIdentity(part) {
3702
3735
  return {
@@ -3765,7 +3798,11 @@ function toV2RequestMessages(messages) {
3765
3798
  continue;
3766
3799
  }
3767
3800
  if (content.length > 0) {
3768
- result.push({ role: message.info.role, content });
3801
+ result.push({
3802
+ role: message.info.role,
3803
+ content,
3804
+ ...message.info.role === "user" && message.info.hostInput ? { id: message.info.id, metadata: message.info.hostInput.metadata } : {}
3805
+ });
3769
3806
  }
3770
3807
  }
3771
3808
  return result;
@@ -4339,8 +4376,7 @@ function appendProtectedUserMessages(summary, selection, searchContext, state, e
4339
4376
  }
4340
4377
  const message = searchContext.rawMessagesById.get(messageId);
4341
4378
  if (!message) continue;
4342
- if (message.info.role !== "user") continue;
4343
- if (isIgnoredUserMessage(message)) continue;
4379
+ if (!isUserPrompt(message)) continue;
4344
4380
  const parts = Array.isArray(message.parts) ? message.parts : [];
4345
4381
  for (const part of parts) {
4346
4382
  if (part.type === "text" && typeof part.text === "string" && part.text.trim()) {
@@ -4367,8 +4403,7 @@ function appendProtectedPromptInfo(summary, selection, searchContext, state, ena
4367
4403
  }
4368
4404
  const message = searchContext.rawMessagesById.get(messageId);
4369
4405
  if (!message) continue;
4370
- if (message.info.role !== "user") continue;
4371
- if (isIgnoredUserMessage(message)) continue;
4406
+ if (!isUserPrompt(message)) continue;
4372
4407
  const parts = Array.isArray(message.parts) ? message.parts : [];
4373
4408
  for (const part of parts) {
4374
4409
  if (part.type !== "text" || typeof part.text !== "string") continue;
@@ -4469,9 +4504,7 @@ function filterProtectedToolMessages(selection, searchContext, protectedTools, p
4469
4504
  if (removedMessageIds.size === 0) {
4470
4505
  return selection;
4471
4506
  }
4472
- const filteredMessageIds = selection.messageIds.filter(
4473
- (id) => !removedMessageIds.has(id)
4474
- );
4507
+ const filteredMessageIds = selection.messageIds.filter((id) => !removedMessageIds.has(id));
4475
4508
  const filteredMessageTokenById = /* @__PURE__ */ new Map();
4476
4509
  for (const id of filteredMessageIds) {
4477
4510
  const tokens = selection.messageTokenById.get(id);
@@ -4495,13 +4528,10 @@ function filterLastUserMessage(selection, searchContext, state, compress) {
4495
4528
  const msg = searchContext.rawMessages[i];
4496
4529
  const id = msg?.info?.id;
4497
4530
  if (!id || typeof id !== "string") continue;
4498
- if (isSyntheticMessage(msg)) continue;
4499
- if (isIgnoredUserMessage(msg)) continue;
4531
+ if (!isUserPrompt(msg)) continue;
4500
4532
  if (state.prune.messages.byMessageId.has(id)) continue;
4501
- if (msg.info.role === "user") {
4502
- lastUserMessageId = id;
4503
- break;
4504
- }
4533
+ lastUserMessageId = id;
4534
+ break;
4505
4535
  }
4506
4536
  if (!lastUserMessageId || !selection.messageIds.includes(lastUserMessageId)) {
4507
4537
  return selection;
@@ -4786,7 +4816,8 @@ function collectCompressInvocations(messages) {
4786
4816
  invocations.push({
4787
4817
  messageId: message.info.id,
4788
4818
  callId: typeof part.callID === "string" ? part.callID : void 0,
4789
- input
4819
+ input,
4820
+ hostInputRefs: part.state?.metadata?.acpHostInputRefs === true
4790
4821
  });
4791
4822
  }
4792
4823
  }
@@ -4871,8 +4902,25 @@ function translateIds(ids, mapped) {
4871
4902
  }
4872
4903
  function restoreForkCompressionState(state, forkMessages, parent, parentMessages, logger) {
4873
4904
  if (!parent.prune.messages || !parent.messageIds) return 0;
4874
- assignMessageRefs(state, forkMessages);
4875
- const mapped = mapForkIds(state, parent, parentMessages, forkMessages);
4905
+ if (state.messageIds.byRawId.size === 0 && parentMessages.some(
4906
+ (message) => isHostInput(message) && parent.messageIds?.byRawId[message.info.id]
4907
+ )) {
4908
+ return 0;
4909
+ }
4910
+ const forkState = {
4911
+ ...state,
4912
+ messageIds: {
4913
+ ...state.messageIds,
4914
+ byRawId: new Map(state.messageIds.byRawId),
4915
+ byRef: new Map(state.messageIds.byRef)
4916
+ }
4917
+ };
4918
+ assignMessageRefs(
4919
+ forkState,
4920
+ forkMessages.filter((message) => !isHostInput(message))
4921
+ );
4922
+ assignMessageRefs(forkState, forkMessages);
4923
+ const mapped = mapForkIds(forkState, parent, parentMessages, forkMessages);
4876
4924
  if (!mapped) return 0;
4877
4925
  const parentBlocks = Object.values(parent.prune.messages.blocksById);
4878
4926
  const translatedBlocks = /* @__PURE__ */ new Map();
@@ -4935,6 +4983,7 @@ function restoreForkCompressionState(state, forkMessages, parent, parentMessages
4935
4983
  messagesState.nextRunId = parent.prune.messages.nextRunId;
4936
4984
  messagesState.membershipsVerified = true;
4937
4985
  state.prune.messages = messagesState;
4986
+ state.messageIds = forkState.messageIds;
4938
4987
  logger.info("fork: restored compression state from parent", {
4939
4988
  blocks: copiedBlockIds.size,
4940
4989
  activeBlocks: messagesState.activeBlockIds.size
@@ -5053,17 +5102,38 @@ function rebuildMessageInvocation(state, input, searchContext, invocation, gcCon
5053
5102
  return created;
5054
5103
  }
5055
5104
  function rebuildCompressionState(state, messages, config, logger) {
5056
- assignMessageRefs(state, messages);
5057
5105
  const invocations = collectCompressInvocations(messages);
5058
5106
  if (invocations.length === 0) {
5107
+ assignMessageRefs(state, messages);
5059
5108
  return 0;
5060
5109
  }
5110
+ const existingRefs = new Map(state.messageIds.byRef);
5111
+ const hasHostInputs = messages.some(isHostInput);
5112
+ const legacyMessages = messages.filter((message) => !isHostInput(message));
5113
+ assignMessageRefs(state, legacyMessages);
5114
+ assignMessageRefs(state, messages);
5061
5115
  const protectedTools = config.compress.protectedTools;
5062
5116
  const protectedFilePatterns = config.protectedFilePatterns;
5063
5117
  const gcConfig = config.gc;
5064
5118
  let rebuilt = 0;
5065
5119
  for (const invocation of invocations) {
5066
- const searchContext = buildSearchContext(state, messages);
5120
+ if (invocation.hostInputRefs && hasHostInputs) {
5121
+ const content = invocation.input.content;
5122
+ const hasReliableRefs = existingRefs.size > 0 && Array.isArray(content) && content.every((entry) => {
5123
+ const refs = isRangeInput(invocation.input) ? [entry?.startId, entry?.endId] : [entry?.messageId];
5124
+ return refs.every(
5125
+ (ref) => typeof ref === "string" && (parseMessageRef(ref) === null || existingRefs.has(ref.trim().toLowerCase()))
5126
+ );
5127
+ });
5128
+ if (!hasReliableRefs) {
5129
+ logger.warn("rebuild: host-input aliases unavailable, stopping history replay");
5130
+ break;
5131
+ }
5132
+ }
5133
+ const searchContext = buildSearchContext(
5134
+ state,
5135
+ invocation.hostInputRefs ? messages : legacyMessages
5136
+ );
5067
5137
  try {
5068
5138
  if (isRangeInput(invocation.input)) {
5069
5139
  rebuilt += rebuildRangeInvocation(
@@ -5266,6 +5336,7 @@ function createSessionState() {
5266
5336
  }
5267
5337
  function resetSessionState(state) {
5268
5338
  state.sessionId = null;
5339
+ state.visibleHostInputIds = void 0;
5269
5340
  state.isSubAgent = false;
5270
5341
  state.compressPermission = void 0;
5271
5342
  state.prune = {
@@ -5517,7 +5588,7 @@ function cacheSystemPromptTokens(state, messages) {
5517
5588
  }
5518
5589
  let firstUserText = "";
5519
5590
  for (const msg of messages) {
5520
- if (msg.info.role !== "user" || isIgnoredUserMessage(msg)) {
5591
+ if (!isUserPrompt(msg)) {
5521
5592
  continue;
5522
5593
  }
5523
5594
  const parts = Array.isArray(msg.parts) ? msg.parts : [];
@@ -5740,7 +5811,8 @@ ${message}`);
5740
5811
  await client.session.synthetic({
5741
5812
  sessionID: sessionId,
5742
5813
  text: toastMessage,
5743
- description: "ACP: Compress Notification"
5814
+ description: "ACP: Compress Notification",
5815
+ metadata: { source: "opencode-acp" }
5744
5816
  });
5745
5817
  return true;
5746
5818
  }
@@ -5749,7 +5821,8 @@ async function sendIgnoredMessage(client, sessionID, text, params, logger) {
5749
5821
  await client.session.synthetic({
5750
5822
  sessionID,
5751
5823
  text,
5752
- description: "ACP"
5824
+ description: "ACP",
5825
+ metadata: { source: "opencode-acp" }
5753
5826
  });
5754
5827
  } catch (error) {
5755
5828
  logger.error("Failed to send notification", { error: error.message });
@@ -6604,9 +6677,14 @@ function restoreCompressionState(state, snapshot) {
6604
6677
  state.prune.messages = structuredClone(snapshot.messages);
6605
6678
  state.stats = { ...snapshot.stats };
6606
6679
  }
6680
+ function filterUnseenHostInputs(state, messages) {
6681
+ return messages.filter(
6682
+ (message) => !isHostInput(message) || state.visibleHostInputIds?.has(message.info.id) === true || (state.prune.messages.byMessageId.get(message.info.id)?.activeBlockIds.length ?? 0) > 0
6683
+ );
6684
+ }
6607
6685
  async function prepareSession(ctx, toolCtx, title) {
6608
6686
  await ctx.assertPermission(toolCtx.sessionID);
6609
- const rawMessages = await fetchSessionMessages(ctx.client, toolCtx.sessionID);
6687
+ let rawMessages = await fetchSessionMessages(ctx.client, toolCtx.sessionID);
6610
6688
  await ensureSessionInitialized(
6611
6689
  ctx.client,
6612
6690
  ctx.state,
@@ -6615,6 +6693,7 @@ async function prepareSession(ctx, toolCtx, title) {
6615
6693
  rawMessages,
6616
6694
  ctx.config
6617
6695
  );
6696
+ rawMessages = filterUnseenHostInputs(ctx.state, rawMessages);
6618
6697
  assignMessageRefs(ctx.state, rawMessages);
6619
6698
  return {
6620
6699
  rawMessages,
@@ -7321,7 +7400,7 @@ function countMessagesAfterIndex(messages, index) {
7321
7400
  return count;
7322
7401
  }
7323
7402
  function getModelInfo(messages) {
7324
- const lastUserMessage = getLastUserMessage(messages);
7403
+ const lastUserMessage = getRequestInput(messages);
7325
7404
  if (!lastUserMessage) {
7326
7405
  return {
7327
7406
  providerId: void 0,
@@ -7542,7 +7621,7 @@ function collectTurnNudgeAnchors2(state, config, messages) {
7542
7621
  const targetRole = config.compress.nudgeForce === "strong" ? "user" : "assistant";
7543
7622
  for (const message of messages) {
7544
7623
  if (!state.nudges.turnNudgeAnchors.has(message.info.id)) continue;
7545
- if (message.info.role === targetRole) {
7624
+ if (targetRole === "user" ? isUserPrompt(message) : message.info.role === targetRole) {
7546
7625
  turnNudgeAnchors.add(message.info.id);
7547
7626
  }
7548
7627
  }
@@ -7716,7 +7795,6 @@ function buildCompressibleRanges(messages, state, protectedTools = [], protected
7716
7795
  if (isSyntheticMessage(msg)) continue;
7717
7796
  const ref = state.messageIds.byRawId.get(msg.info.id);
7718
7797
  if (!ref) continue;
7719
- const rn = parseInt(ref.slice(1), 10);
7720
7798
  if ((protectedTools.length > 0 || protectedFilePatterns.length > 0) && messageContainsProtectedTool(msg, protectedTools, protectedFilePatterns)) {
7721
7799
  const tokens2 = Math.round(countMessageCharacters(msg) / 4);
7722
7800
  const tools = /* @__PURE__ */ new Set();
@@ -7739,7 +7817,7 @@ function buildCompressibleRanges(messages, state, protectedTools = [], protected
7739
7817
  }
7740
7818
  }
7741
7819
  }
7742
- protectedMsgInfo.push({ ref, refNum: rn, tokens: tokens2, tools: [...tools] });
7820
+ protectedMsgInfo.push({ ref, rawIndex: mi, tokens: tokens2, tools: [...tools] });
7743
7821
  continue;
7744
7822
  }
7745
7823
  const tokens = Math.round(countMessageCharacters(msg) / 4);
@@ -7753,18 +7831,18 @@ function buildCompressibleRanges(messages, state, protectedTools = [], protected
7753
7831
  hasMeaningfulPart = true;
7754
7832
  }
7755
7833
  }
7756
- if (msg.info.role === "user" && !isIgnoredUserMessage(msg)) {
7834
+ if (isUserPrompt(msg)) {
7757
7835
  lastUserRefIdx.length = 0;
7758
7836
  lastUserRefIdx.push(msgInfo.length);
7759
7837
  }
7760
7838
  msgInfo.push({
7761
7839
  ref,
7762
- refNum: rn,
7840
+ rawIndex: mi,
7763
7841
  tokens,
7764
7842
  effectiveTokens: 0,
7765
7843
  meaningful: hasMeaningfulPart,
7766
7844
  isTool,
7767
- isUser: msg.info.role === "user"
7845
+ isUser: isUserPrompt(msg)
7768
7846
  });
7769
7847
  }
7770
7848
  const lastUserIdx = lastUserRefIdx.length > 0 ? lastUserRefIdx[0] : -1;
@@ -7774,26 +7852,28 @@ function buildCompressibleRanges(messages, state, protectedTools = [], protected
7774
7852
  }
7775
7853
  const groups = [];
7776
7854
  let cur = null;
7777
- let prevRefNum = -2;
7855
+ let previousIndex = -2;
7778
7856
  for (const info of msgInfo) {
7779
7857
  if (protectedZoneRefs?.has(info.ref)) {
7780
7858
  if (cur) {
7781
7859
  groups.push(cur);
7782
7860
  cur = null;
7783
7861
  }
7784
- prevRefNum = info.refNum;
7862
+ previousIndex = info.rawIndex;
7785
7863
  continue;
7786
7864
  }
7787
- const hasGap = info.refNum !== prevRefNum + 1;
7865
+ const hasGap = info.rawIndex !== previousIndex + 1;
7788
7866
  if (cur && (info.isUser && cur.count >= 3 || hasGap)) {
7789
7867
  groups.push(cur);
7790
7868
  cur = null;
7791
7869
  }
7792
- prevRefNum = info.refNum;
7870
+ previousIndex = info.rawIndex;
7793
7871
  if (!cur) {
7794
7872
  cur = {
7795
7873
  startRef: info.ref,
7796
7874
  endRef: info.ref,
7875
+ startIndex: info.rawIndex,
7876
+ endIndex: info.rawIndex,
7797
7877
  count: 1,
7798
7878
  tokens: info.tokens,
7799
7879
  effectiveTokens: info.effectiveTokens,
@@ -7802,6 +7882,7 @@ function buildCompressibleRanges(messages, state, protectedTools = [], protected
7802
7882
  };
7803
7883
  } else {
7804
7884
  cur.endRef = info.ref;
7885
+ cur.endIndex = info.rawIndex;
7805
7886
  cur.count++;
7806
7887
  cur.tokens += info.tokens;
7807
7888
  cur.effectiveTokens += info.effectiveTokens;
@@ -7816,24 +7897,27 @@ function buildCompressibleRanges(messages, state, protectedTools = [], protected
7816
7897
  if (cur) groups.push(cur);
7817
7898
  const protectedGroups = [];
7818
7899
  let pcur = null;
7819
- let pPrevRefNum = -2;
7900
+ let previousProtectedIndex = -2;
7820
7901
  for (const info of protectedMsgInfo) {
7821
- const hasGap = info.refNum > pPrevRefNum + 1;
7902
+ const hasGap = info.rawIndex !== previousProtectedIndex + 1;
7822
7903
  if (pcur && hasGap) {
7823
7904
  protectedGroups.push(pcur);
7824
7905
  pcur = null;
7825
7906
  }
7826
- pPrevRefNum = info.refNum;
7907
+ previousProtectedIndex = info.rawIndex;
7827
7908
  if (!pcur) {
7828
7909
  pcur = {
7829
7910
  startRef: info.ref,
7830
7911
  endRef: info.ref,
7912
+ startIndex: info.rawIndex,
7913
+ endIndex: info.rawIndex,
7831
7914
  count: 1,
7832
7915
  tokens: info.tokens,
7833
7916
  tools: [...info.tools]
7834
7917
  };
7835
7918
  } else {
7836
7919
  pcur.endRef = info.ref;
7920
+ pcur.endIndex = info.rawIndex;
7837
7921
  pcur.count++;
7838
7922
  pcur.tokens += info.tokens;
7839
7923
  for (const t of info.tools) {
@@ -7894,8 +7978,8 @@ ${lines2.join("\n")}`;
7894
7978
  entries.push({
7895
7979
  startRef: r.startRef,
7896
7980
  endRef: r.endRef,
7897
- startNum: refNum(r.startRef),
7898
- endNum: refNum(r.endRef),
7981
+ startIndex: r.startIndex,
7982
+ endIndex: r.endIndex,
7899
7983
  count: r.count,
7900
7984
  tokens: r.tokens,
7901
7985
  toolPct: r.toolPct,
@@ -7912,8 +7996,8 @@ ${lines2.join("\n")}`;
7912
7996
  entries.push({
7913
7997
  startRef: r.startRef,
7914
7998
  endRef: r.endRef,
7915
- startNum: refNum(r.startRef),
7916
- endNum: refNum(r.endRef),
7999
+ startIndex: r.startIndex,
8000
+ endIndex: r.endIndex,
7917
8001
  count: r.count,
7918
8002
  tokens: r.tokens,
7919
8003
  toolPct: 0,
@@ -7926,13 +8010,15 @@ ${lines2.join("\n")}`;
7926
8010
  dangerous: false
7927
8011
  });
7928
8012
  }
7929
- entries.sort((a, b) => a.startNum - b.startNum);
8013
+ entries.sort(
8014
+ (a, b) => (a.startIndex ?? refNum(a.startRef)) - (b.startIndex ?? refNum(b.startRef))
8015
+ );
7930
8016
  const merged = [];
7931
8017
  for (const entry of entries) {
7932
8018
  const last = merged[merged.length - 1];
7933
- if (last && entry.startNum <= last.endNum + 1) {
8019
+ if (last && last.endIndex !== void 0 && entry.startIndex === last.endIndex + 1 && last.protectedCount > 0 === entry.protectedCount > 0) {
7934
8020
  last.endRef = entry.endRef;
7935
- last.endNum = Math.max(last.endNum, entry.endNum);
8021
+ last.endIndex = entry.endIndex;
7936
8022
  last.count += entry.count;
7937
8023
  last.tokens += entry.tokens;
7938
8024
  last.compressibleTokens += entry.compressibleTokens;
@@ -7980,7 +8066,7 @@ function computeProtectedRefs(messages, state, compress) {
7980
8066
  tokens += Math.round(JSON.stringify(part).length / 4);
7981
8067
  }
7982
8068
  }
7983
- visible.push({ ref, tokens, isUser: msg.info.role === "user" });
8069
+ visible.push({ ref, tokens, isUser: isUserPrompt(msg) });
7984
8070
  }
7985
8071
  if (preserveN > 0) {
7986
8072
  for (const m of visible.slice(-preserveN)) {
@@ -8005,15 +8091,15 @@ function excludeProtectedRanges(ranges, protectedRefs) {
8005
8091
  var SMART_PLAN_TTL_MS = 10 * 60 * 1e3;
8006
8092
  var armedPlans = /* @__PURE__ */ new Map();
8007
8093
  var visibleMessageIdsBySession = /* @__PURE__ */ new Map();
8008
- function refNumber(ref) {
8009
- const value = Number.parseInt(ref.slice(1), 10);
8010
- return Number.isFinite(value) ? value : -1;
8011
- }
8012
- function mergeAdjacentSafeRanges(ranges) {
8094
+ function mergeAdjacentSafeRanges(ranges, searchContext, ctx) {
8013
8095
  const merged = [];
8014
8096
  for (const range of ranges.filter((candidate) => !candidate.dangerous)) {
8015
8097
  const previous = merged.at(-1);
8016
- if (previous && refNumber(range.startRef) === refNumber(previous.endRef) + 1) {
8098
+ const startId = ctx.state.messageIds.byRef.get(range.startRef);
8099
+ const previousEndId = previous && ctx.state.messageIds.byRef.get(previous.endRef);
8100
+ const startIndex = startId && searchContext.rawIndexById.get(startId);
8101
+ const previousEndIndex = previousEndId && searchContext.rawIndexById.get(previousEndId);
8102
+ if (previous && typeof startIndex === "number" && typeof previousEndIndex === "number" && startIndex === previousEndIndex + 1) {
8017
8103
  const previousEffective = previous.effectiveTokens ?? previous.tokens;
8018
8104
  previous.endRef = range.endRef;
8019
8105
  previous.count += range.count;
@@ -8069,7 +8155,7 @@ function filteredSelection(startId, endId, searchContext, ctx) {
8069
8155
  }
8070
8156
  function armBestSmartPlan(sessionID, ranges, searchContext, ctx, visibleMessageIds, now = Date.now(), targetChars = ctx.config.compress.minCompressRange) {
8071
8157
  const candidates = [];
8072
- for (const range of mergeAdjacentSafeRanges(ranges)) {
8158
+ for (const range of mergeAdjacentSafeRanges(ranges, searchContext, ctx)) {
8073
8159
  const selection = filteredSelection(range.startRef, range.endRef, searchContext, ctx);
8074
8160
  if (!selection || selection.messageIds.length === 0) continue;
8075
8161
  if (visibleMessageIds && !selection.messageIds.every((id) => visibleMessageIds.has(id)))
@@ -8456,6 +8542,7 @@ function createCompressRangeTool(factoryCtx) {
8456
8542
  \u26A0\uFE0F acknowledgeRisk was ignored: no quality gate rejection was pending, so quality checks ran normally. Only pass it when retrying immediately after a quality gate rejection.
8457
8543
  ` : "";
8458
8544
  return {
8545
+ metadata: { acpHostInputRefs: true },
8459
8546
  content: `Compressed ${totalCompressedMessages} messages into ${COMPRESSED_BLOCK_HEADER}.${skippedNote}${ackNote}
8460
8547
  IMPORTANT: This was an automatic context compression. You MUST continue your previous task exactly where you left off. Do NOT ask the user what to do next.
8461
8548
  \u{1F4A1} Tip: Use acp_search_context('keyword') to find compressed content when you need it later.`
@@ -8520,7 +8607,7 @@ var filterCompressedRanges = (state, messages) => {
8520
8607
  }
8521
8608
  return false;
8522
8609
  });
8523
- const firstUserIdx = messages.findIndex((msg) => msg.info.role === "user");
8610
+ const firstUserIdx = messages.findIndex(isUserPrompt);
8524
8611
  if (firstUserIdx >= 0) {
8525
8612
  survive[firstUserIdx] = true;
8526
8613
  }
@@ -8530,6 +8617,20 @@ var filterCompressedRanges = (state, messages) => {
8530
8617
  result.push(messages[i]);
8531
8618
  }
8532
8619
  }
8620
+ if (!result.some((message) => message.info.role === "user")) {
8621
+ const compressedHostInput = messages.find(
8622
+ (message, index) => !survive[index] && isHostInput(message)
8623
+ );
8624
+ if (compressedHostInput) {
8625
+ result.unshift(
8626
+ createSyntheticUserMessage(
8627
+ compressedHostInput,
8628
+ "Earlier host input has been compressed.",
8629
+ "acp-compressed-host-input"
8630
+ )
8631
+ );
8632
+ }
8633
+ }
8533
8634
  messages.length = 0;
8534
8635
  messages.push(...result);
8535
8636
  };
@@ -9328,9 +9429,7 @@ var injectCompressNudges = (state, config, logger, messages, prompts, compressio
9328
9429
  modelId,
9329
9430
  messages
9330
9431
  );
9331
- const lastUserIdx = messages.findLastIndex(
9332
- (m) => m.info.role === "user" && !isIgnoredUserMessage(m)
9333
- );
9432
+ const lastUserIdx = messages.findLastIndex(isUserPrompt);
9334
9433
  const currentTurnStart = lastUserIdx >= 0 ? lastUserIdx + 1 : 0;
9335
9434
  const currentTurnHasCompress = messages.slice(currentTurnStart).some((m) => m.info.role === "assistant" && messageHasCompressAttempt(m));
9336
9435
  if (currentTurnHasCompress) {
@@ -9410,7 +9509,7 @@ var injectCompressNudges = (state, config, logger, messages, prompts, compressio
9410
9509
  anchorsChanged = true;
9411
9510
  }
9412
9511
  if (overMinLimit) {
9413
- const isLastMessageUser = lastMessage?.message.info.role === "user";
9512
+ const isLastMessageUser = lastMessage && isUserPrompt(lastMessage.message);
9414
9513
  if (isLastMessageUser && lastAssistantMessage) {
9415
9514
  const previousSize = state.nudges.turnNudgeAnchors.size;
9416
9515
  state.nudges.turnNudgeAnchors.add(lastMessage.message.info.id);
@@ -11206,7 +11305,10 @@ function createAcpStatusToolV2(factoryCtx) {
11206
11305
  }
11207
11306
  let rawMessages = [];
11208
11307
  try {
11209
- rawMessages = await fetchSessionMessages(ctx.client, toolCtx.sessionID);
11308
+ rawMessages = filterUnseenHostInputs(
11309
+ ctx.state,
11310
+ await fetchSessionMessages(ctx.client, toolCtx.sessionID)
11311
+ );
11210
11312
  } catch {
11211
11313
  if (scope === "uncompressed") return { content: "(unable to fetch messages)" };
11212
11314
  }
@@ -11415,7 +11517,7 @@ import { writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
11415
11517
  import { join as join5 } from "path";
11416
11518
  import { existsSync as existsSync5 } from "fs";
11417
11519
  import { homedir as homedir3 } from "os";
11418
- var LOG_VERSION = true ? "2.0.0-alpha.7" : "dev";
11520
+ var LOG_VERSION = true ? "2.0.0-alpha.8" : "dev";
11419
11521
  var LEVEL_RANK = {
11420
11522
  debug: 10,
11421
11523
  info: 20,
@@ -13213,11 +13315,11 @@ function runBatchCleanup(state, config, logger, messages, prePruneTokens) {
13213
13315
  // src/v2/hooks/messages.ts
13214
13316
  var INTERNAL_AGENT_NAMES = /* @__PURE__ */ new Set(["title", "summary", "compaction"]);
13215
13317
  function isInternalAgentRequest(messages) {
13216
- const lastUserMessage = getLastUserMessage(messages);
13217
- if (!lastUserMessage) {
13318
+ const requestInput = getRequestInput(messages);
13319
+ if (!requestInput) {
13218
13320
  return false;
13219
13321
  }
13220
- const agent = lastUserMessage.info.agent;
13322
+ const agent = requestInput.info.agent;
13221
13323
  return typeof agent === "string" && INTERNAL_AGENT_NAMES.has(agent);
13222
13324
  }
13223
13325
  function createChatMessageTransformHandler(client, registry4, logger, config, prompts, hostPermissions) {
@@ -13240,19 +13342,19 @@ function createChatMessageTransformHandler(client, registry4, logger, config, pr
13240
13342
  return;
13241
13343
  }
13242
13344
  checkpoint("resolveSession");
13243
- const lastUserMessage = getLastUserMessage(messages);
13345
+ const requestInput = getRequestInput(messages);
13244
13346
  let state;
13245
- if (!lastUserMessage) {
13347
+ if (!requestInput) {
13246
13348
  state = createSessionState();
13247
13349
  } else {
13248
13350
  state = await registry4.getOrCreate(
13249
13351
  client,
13250
- lastUserMessage.info.sessionID,
13352
+ requestInput.info.sessionID,
13251
13353
  messages,
13252
13354
  config
13253
13355
  );
13254
13356
  checkpoint("resolveModel");
13255
- const requestModel = lastUserMessage.info.model;
13357
+ const requestModel = requestInput.info.model;
13256
13358
  let requestModelLimit = registry4.resolveModelLimit(
13257
13359
  requestModel?.providerID,
13258
13360
  requestModel?.modelID
@@ -13319,7 +13421,7 @@ function createChatMessageTransformHandler(client, registry4, logger, config, pr
13319
13421
  checkpoint("stripHallucinations");
13320
13422
  stripHallucinations(output.messages);
13321
13423
  checkpoint("dropReasoning");
13322
- const dropReasoningModel = lastUserMessage?.info?.model;
13424
+ const dropReasoningModel = requestInput?.info?.model;
13323
13425
  const reasoningConfig = applyCompressOverrides(
13324
13426
  config,
13325
13427
  dropReasoningModel?.providerID ?? state.modelProviderID,
@@ -13550,7 +13652,7 @@ function analyzeTokens(state, messages) {
13550
13652
  const isCompacted = isMessageCompacted(state, msg);
13551
13653
  const pruneEntry = state.prune.messages.byMessageId.get(msg.info.id);
13552
13654
  const isMessagePruned = !!pruneEntry && pruneEntry.activeBlockIds.length > 0;
13553
- const isIgnoredUser = isIgnoredUserMessage(msg);
13655
+ const isHumanPrompt = isUserPrompt(msg);
13554
13656
  for (const part of parts) {
13555
13657
  if (part.type === "tool") {
13556
13658
  const toolPart = part;
@@ -13573,7 +13675,7 @@ function analyzeTokens(state, messages) {
13573
13675
  toolOutputParts.push(outputStr);
13574
13676
  }
13575
13677
  }
13576
- } else if (part.type === "text" && msg.info.role === "user" && !isCompacted && !isIgnoredUser) {
13678
+ } else if (part.type === "text" && isHumanPrompt && !isCompacted) {
13577
13679
  const textPart = part;
13578
13680
  const text = textPart.text || "";
13579
13681
  userTextParts.push(text);
@@ -13582,7 +13684,7 @@ function analyzeTokens(state, messages) {
13582
13684
  }
13583
13685
  }
13584
13686
  }
13585
- if (msg.info.role === "user" && !isIgnoredUser && !foundFirstUser) {
13687
+ if (isHumanPrompt && !foundFirstUser) {
13586
13688
  foundFirstUser = true;
13587
13689
  }
13588
13690
  }
@@ -14350,7 +14452,12 @@ async function notifySession(ctx, title, message) {
14350
14452
  const sessions = Array.isArray(response) ? response : response.data ?? [];
14351
14453
  const sessionID = Array.isArray(sessions) && typeof sessions[0]?.id === "string" ? sessions[0].id : void 0;
14352
14454
  if (sessionID) {
14353
- await ctx.session.synthetic({ sessionID, text: message, description: title });
14455
+ await ctx.session.synthetic({
14456
+ sessionID,
14457
+ text: message,
14458
+ description: title,
14459
+ metadata: { source: "opencode-acp" }
14460
+ });
14354
14461
  }
14355
14462
  } catch {
14356
14463
  }
@@ -14460,14 +14567,14 @@ var AcpV2Plugin = Plugin.define({
14460
14567
  await diagnoseContext(logger, event.sessionID, async (diagnostic) => {
14461
14568
  const timeline = diagnostic?.timeline("context", "fetchSessionMessages");
14462
14569
  const checkpoint = (stage) => timeline?.next(stage);
14463
- const messages = await fetchV2SessionMessages(ctx, event.sessionID);
14570
+ const messages = await fetchV2SessionMessages(ctx, event.sessionID, event.messages);
14464
14571
  checkpoint("prepareMessages");
14465
14572
  if (diagnostic) diagnostic.counts.inputMessages = messages.length;
14466
14573
  if (messages.length === 0) {
14467
14574
  diagnostic?.skip("empty_history");
14468
14575
  return;
14469
14576
  }
14470
- const lastUser = [...messages].reverse().find((message) => message.info.role === "user");
14577
+ const lastUser = getRequestInput(messages);
14471
14578
  if (lastUser?.info.role === "user") {
14472
14579
  lastUser.info.agent = event.agent;
14473
14580
  lastUser.info.model = {
@@ -14483,6 +14590,12 @@ var AcpV2Plugin = Plugin.define({
14483
14590
  if (diagnostic) diagnostic.counts.outputMessages = output.messages.length;
14484
14591
  checkpoint("convertRequestMessages");
14485
14592
  event.messages = toV2RequestMessages(output.messages);
14593
+ const state = registry4.get(event.sessionID);
14594
+ if (state) {
14595
+ state.visibleHostInputIds = new Set(
14596
+ output.messages.filter(isHostInput).map((message) => message.info.id)
14597
+ );
14598
+ }
14486
14599
  checkpoint("transformSystem");
14487
14600
  const systemOutput = {
14488
14601
  system: event.system.map((part) => part.text)