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

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;
@@ -3558,7 +3568,7 @@ function applyPendingCompressionDurations(state) {
3558
3568
  }
3559
3569
 
3560
3570
  // src/state/model-limits.ts
3561
- function createModelLimitCatalog() {
3571
+ function createModelLimitCatalog(logger) {
3562
3572
  const modelLimits = /* @__PURE__ */ new Map();
3563
3573
  return {
3564
3574
  record(providerId, modelId, limit) {
@@ -3570,14 +3580,27 @@ function createModelLimitCatalog() {
3570
3580
  return modelLimits.get(`${providerId}/${modelId}`);
3571
3581
  },
3572
3582
  /**
3573
- * Best-effort one-time seed from the V2 model catalog. Never throws;
3583
+ * Best-effort load from the V2 model catalog. Never throws;
3574
3584
  * returns the number of model-limit entries recorded.
3575
3585
  */
3576
3586
  async hydrateFromClient(client) {
3577
3587
  try {
3578
3588
  const v2Client = client;
3589
+ if (typeof v2Client?.model?.list !== "function") {
3590
+ logger?.warn("Model limit catalog load failed", {
3591
+ reason: "api_unavailable",
3592
+ catalogSize: modelLimits.size
3593
+ });
3594
+ return 0;
3595
+ }
3579
3596
  const response = await v2Client.model.list();
3580
- if (!Array.isArray(response.data)) return 0;
3597
+ if (!Array.isArray(response?.data)) {
3598
+ logger?.warn("Model limit catalog load failed", {
3599
+ reason: "invalid_response",
3600
+ catalogSize: modelLimits.size
3601
+ });
3602
+ return 0;
3603
+ }
3581
3604
  let recorded = 0;
3582
3605
  for (const value of response.data) {
3583
3606
  if (!value || typeof value !== "object") continue;
@@ -3588,8 +3611,19 @@ function createModelLimitCatalog() {
3588
3611
  modelLimits.set(`${model.providerID}/${model.id}`, model.limit.context);
3589
3612
  recorded++;
3590
3613
  }
3614
+ logger?.info("Model limit catalog loaded", {
3615
+ reason: response.data.length === 0 ? "empty_catalog" : recorded === 0 ? "no_valid_limits" : "loaded",
3616
+ entries: response.data.length,
3617
+ recorded,
3618
+ skipped: response.data.length - recorded,
3619
+ catalogSize: modelLimits.size
3620
+ });
3591
3621
  return recorded;
3592
3622
  } catch {
3623
+ logger?.warn("Model limit catalog load failed", {
3624
+ reason: "request_failed",
3625
+ catalogSize: modelLimits.size
3626
+ });
3593
3627
  return 0;
3594
3628
  }
3595
3629
  }
@@ -3626,12 +3660,13 @@ function convertToolPart(part) {
3626
3660
  state: {
3627
3661
  status,
3628
3662
  input: state?.input ?? part.input,
3629
- output: textFromContent(output)
3663
+ output: textFromContent(output),
3664
+ ...state?.metadata?.acpHostInputRefs === true ? { metadata: { acpHostInputRefs: true } } : {}
3630
3665
  }
3631
3666
  };
3632
3667
  }
3633
3668
  function convertParts(message) {
3634
- if (message.type === "user") {
3669
+ if (message.type === "user" || message.type === "synthetic") {
3635
3670
  const parts2 = [];
3636
3671
  if (typeof message.text === "string") {
3637
3672
  parts2.push({ type: "text", text: message.text });
@@ -3657,19 +3692,35 @@ function convertParts(message) {
3657
3692
  }
3658
3693
  return parts;
3659
3694
  }
3660
- function fromV2SessionMessages(input, sessionID) {
3695
+ function isAcpNotification(message) {
3696
+ return message.metadata?.source === "opencode-acp" || message.metadata?.source === void 0 && (message.description === "ACP" || message.description === "ACP update ready" || message.description?.startsWith("ACP:") === true);
3697
+ }
3698
+ function fromV2SessionMessages(input, sessionID, requestMessages) {
3661
3699
  if (!Array.isArray(input)) return [];
3700
+ const requestInputs = /* @__PURE__ */ new Map();
3701
+ for (const value of requestMessages ?? []) {
3702
+ if (!value || typeof value !== "object") continue;
3703
+ const message = value;
3704
+ if (message.role === "user" && typeof message.id === "string") {
3705
+ requestInputs.set(message.id, message);
3706
+ }
3707
+ }
3662
3708
  const result = [];
3663
3709
  for (const value of input) {
3664
3710
  if (!value || typeof value !== "object") continue;
3665
3711
  const message = value;
3666
- if (message.type !== "user" && message.type !== "assistant") continue;
3712
+ const hostInput = message.type === "synthetic";
3713
+ if (!hostInput && message.type !== "user" && message.type !== "assistant") continue;
3667
3714
  if (typeof message.id !== "string") continue;
3668
- const role = message.type;
3715
+ const requestInput = requestInputs.get(message.id);
3716
+ if (hostInput && (isAcpNotification(message) || requestMessages && !requestInput))
3717
+ continue;
3718
+ const role = hostInput ? "user" : message.type;
3669
3719
  const info = {
3670
3720
  id: message.id,
3671
3721
  sessionID,
3672
3722
  role,
3723
+ ...hostInput ? { hostInput: { metadata: requestInput?.metadata ?? message.metadata } } : {},
3673
3724
  time: { created: createdAt(message) },
3674
3725
  agent: message.agent ?? "code",
3675
3726
  model: {
@@ -3684,19 +3735,25 @@ function fromV2SessionMessages(input, sessionID) {
3684
3735
  cost: 0,
3685
3736
  tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }
3686
3737
  };
3738
+ const projectedContent = hostInput ? requestInput?.content : void 0;
3739
+ const parts = typeof projectedContent === "string" ? [{ type: "text", text: projectedContent }] : Array.isArray(projectedContent) ? projectedContent.map((part) => structuredClone(part)) : convertParts(message);
3687
3740
  result.push({
3688
3741
  info,
3689
- parts: convertParts(message)
3742
+ parts
3690
3743
  });
3691
3744
  }
3692
3745
  return result;
3693
3746
  }
3694
- async function fetchV2SessionMessages(client, sessionID) {
3747
+ async function fetchV2SessionMessages(client, sessionID, requestMessages) {
3695
3748
  const runtime = client;
3696
3749
  if (typeof runtime.session?.context !== "function") {
3697
3750
  return [];
3698
3751
  }
3699
- return fromV2SessionMessages(await runtime.session.context({ sessionID }), sessionID);
3752
+ return fromV2SessionMessages(
3753
+ await runtime.session.context({ sessionID }),
3754
+ sessionID,
3755
+ requestMessages
3756
+ );
3700
3757
  }
3701
3758
  function toolIdentity(part) {
3702
3759
  return {
@@ -3765,7 +3822,11 @@ function toV2RequestMessages(messages) {
3765
3822
  continue;
3766
3823
  }
3767
3824
  if (content.length > 0) {
3768
- result.push({ role: message.info.role, content });
3825
+ result.push({
3826
+ role: message.info.role,
3827
+ content,
3828
+ ...message.info.role === "user" && message.info.hostInput ? { id: message.info.id, metadata: message.info.hostInput.metadata } : {}
3829
+ });
3769
3830
  }
3770
3831
  }
3771
3832
  return result;
@@ -4339,8 +4400,7 @@ function appendProtectedUserMessages(summary, selection, searchContext, state, e
4339
4400
  }
4340
4401
  const message = searchContext.rawMessagesById.get(messageId);
4341
4402
  if (!message) continue;
4342
- if (message.info.role !== "user") continue;
4343
- if (isIgnoredUserMessage(message)) continue;
4403
+ if (!isUserPrompt(message)) continue;
4344
4404
  const parts = Array.isArray(message.parts) ? message.parts : [];
4345
4405
  for (const part of parts) {
4346
4406
  if (part.type === "text" && typeof part.text === "string" && part.text.trim()) {
@@ -4367,8 +4427,7 @@ function appendProtectedPromptInfo(summary, selection, searchContext, state, ena
4367
4427
  }
4368
4428
  const message = searchContext.rawMessagesById.get(messageId);
4369
4429
  if (!message) continue;
4370
- if (message.info.role !== "user") continue;
4371
- if (isIgnoredUserMessage(message)) continue;
4430
+ if (!isUserPrompt(message)) continue;
4372
4431
  const parts = Array.isArray(message.parts) ? message.parts : [];
4373
4432
  for (const part of parts) {
4374
4433
  if (part.type !== "text" || typeof part.text !== "string") continue;
@@ -4469,9 +4528,7 @@ function filterProtectedToolMessages(selection, searchContext, protectedTools, p
4469
4528
  if (removedMessageIds.size === 0) {
4470
4529
  return selection;
4471
4530
  }
4472
- const filteredMessageIds = selection.messageIds.filter(
4473
- (id) => !removedMessageIds.has(id)
4474
- );
4531
+ const filteredMessageIds = selection.messageIds.filter((id) => !removedMessageIds.has(id));
4475
4532
  const filteredMessageTokenById = /* @__PURE__ */ new Map();
4476
4533
  for (const id of filteredMessageIds) {
4477
4534
  const tokens = selection.messageTokenById.get(id);
@@ -4495,13 +4552,10 @@ function filterLastUserMessage(selection, searchContext, state, compress) {
4495
4552
  const msg = searchContext.rawMessages[i];
4496
4553
  const id = msg?.info?.id;
4497
4554
  if (!id || typeof id !== "string") continue;
4498
- if (isSyntheticMessage(msg)) continue;
4499
- if (isIgnoredUserMessage(msg)) continue;
4555
+ if (!isUserPrompt(msg)) continue;
4500
4556
  if (state.prune.messages.byMessageId.has(id)) continue;
4501
- if (msg.info.role === "user") {
4502
- lastUserMessageId = id;
4503
- break;
4504
- }
4557
+ lastUserMessageId = id;
4558
+ break;
4505
4559
  }
4506
4560
  if (!lastUserMessageId || !selection.messageIds.includes(lastUserMessageId)) {
4507
4561
  return selection;
@@ -4786,7 +4840,8 @@ function collectCompressInvocations(messages) {
4786
4840
  invocations.push({
4787
4841
  messageId: message.info.id,
4788
4842
  callId: typeof part.callID === "string" ? part.callID : void 0,
4789
- input
4843
+ input,
4844
+ hostInputRefs: part.state?.metadata?.acpHostInputRefs === true
4790
4845
  });
4791
4846
  }
4792
4847
  }
@@ -4871,8 +4926,25 @@ function translateIds(ids, mapped) {
4871
4926
  }
4872
4927
  function restoreForkCompressionState(state, forkMessages, parent, parentMessages, logger) {
4873
4928
  if (!parent.prune.messages || !parent.messageIds) return 0;
4874
- assignMessageRefs(state, forkMessages);
4875
- const mapped = mapForkIds(state, parent, parentMessages, forkMessages);
4929
+ if (state.messageIds.byRawId.size === 0 && parentMessages.some(
4930
+ (message) => isHostInput(message) && parent.messageIds?.byRawId[message.info.id]
4931
+ )) {
4932
+ return 0;
4933
+ }
4934
+ const forkState = {
4935
+ ...state,
4936
+ messageIds: {
4937
+ ...state.messageIds,
4938
+ byRawId: new Map(state.messageIds.byRawId),
4939
+ byRef: new Map(state.messageIds.byRef)
4940
+ }
4941
+ };
4942
+ assignMessageRefs(
4943
+ forkState,
4944
+ forkMessages.filter((message) => !isHostInput(message))
4945
+ );
4946
+ assignMessageRefs(forkState, forkMessages);
4947
+ const mapped = mapForkIds(forkState, parent, parentMessages, forkMessages);
4876
4948
  if (!mapped) return 0;
4877
4949
  const parentBlocks = Object.values(parent.prune.messages.blocksById);
4878
4950
  const translatedBlocks = /* @__PURE__ */ new Map();
@@ -4935,6 +5007,7 @@ function restoreForkCompressionState(state, forkMessages, parent, parentMessages
4935
5007
  messagesState.nextRunId = parent.prune.messages.nextRunId;
4936
5008
  messagesState.membershipsVerified = true;
4937
5009
  state.prune.messages = messagesState;
5010
+ state.messageIds = forkState.messageIds;
4938
5011
  logger.info("fork: restored compression state from parent", {
4939
5012
  blocks: copiedBlockIds.size,
4940
5013
  activeBlocks: messagesState.activeBlockIds.size
@@ -5053,17 +5126,38 @@ function rebuildMessageInvocation(state, input, searchContext, invocation, gcCon
5053
5126
  return created;
5054
5127
  }
5055
5128
  function rebuildCompressionState(state, messages, config, logger) {
5056
- assignMessageRefs(state, messages);
5057
5129
  const invocations = collectCompressInvocations(messages);
5058
5130
  if (invocations.length === 0) {
5131
+ assignMessageRefs(state, messages);
5059
5132
  return 0;
5060
5133
  }
5134
+ const existingRefs = new Map(state.messageIds.byRef);
5135
+ const hasHostInputs = messages.some(isHostInput);
5136
+ const legacyMessages = messages.filter((message) => !isHostInput(message));
5137
+ assignMessageRefs(state, legacyMessages);
5138
+ assignMessageRefs(state, messages);
5061
5139
  const protectedTools = config.compress.protectedTools;
5062
5140
  const protectedFilePatterns = config.protectedFilePatterns;
5063
5141
  const gcConfig = config.gc;
5064
5142
  let rebuilt = 0;
5065
5143
  for (const invocation of invocations) {
5066
- const searchContext = buildSearchContext(state, messages);
5144
+ if (invocation.hostInputRefs && hasHostInputs) {
5145
+ const content = invocation.input.content;
5146
+ const hasReliableRefs = existingRefs.size > 0 && Array.isArray(content) && content.every((entry) => {
5147
+ const refs = isRangeInput(invocation.input) ? [entry?.startId, entry?.endId] : [entry?.messageId];
5148
+ return refs.every(
5149
+ (ref) => typeof ref === "string" && (parseMessageRef(ref) === null || existingRefs.has(ref.trim().toLowerCase()))
5150
+ );
5151
+ });
5152
+ if (!hasReliableRefs) {
5153
+ logger.warn("rebuild: host-input aliases unavailable, stopping history replay");
5154
+ break;
5155
+ }
5156
+ }
5157
+ const searchContext = buildSearchContext(
5158
+ state,
5159
+ invocation.hostInputRefs ? messages : legacyMessages
5160
+ );
5067
5161
  try {
5068
5162
  if (isRangeInput(invocation.input)) {
5069
5163
  rebuilt += rebuildRangeInvocation(
@@ -5115,10 +5209,12 @@ async function updatePerTurnState(state, logger, messages) {
5115
5209
  state.currentTurn = countTurns(state, messages);
5116
5210
  }
5117
5211
  var REGISTRY_SOFT_CAP = 32;
5212
+ var MODEL_LIMIT_RETRY_INTERVAL_MS = 3e4;
5118
5213
  var SessionStateRegistry = class {
5119
5214
  constructor(logger, projectDir) {
5120
5215
  this.logger = logger;
5121
5216
  this.projectDir = projectDir;
5217
+ this.catalog = createModelLimitCatalog(logger);
5122
5218
  }
5123
5219
  logger;
5124
5220
  projectDir;
@@ -5132,38 +5228,41 @@ var SessionStateRegistry = class {
5132
5228
  // model named on the request's user message instead of waiting one turn
5133
5229
  // for the system hook. Shared implementation — the test registry stub
5134
5230
  // composes the same factory.
5135
- catalog = createModelLimitCatalog();
5231
+ catalog;
5136
5232
  recordModelLimit(providerId, modelId, limit) {
5137
5233
  this.catalog.record(providerId, modelId, limit);
5138
5234
  }
5139
5235
  resolveModelLimit(providerId, modelId) {
5140
5236
  return this.catalog.resolve(providerId, modelId);
5141
5237
  }
5142
- /**
5143
- * Best-effort one-time seed from the host's provider catalog
5144
- * V2 model catalog. Never throws; returns the number of model-limit entries recorded.
5145
- * returns the number of model-limit entries recorded.
5146
- */
5238
+ /** Best-effort seed from the V2 model catalog; returns the number of recorded entries. */
5147
5239
  hydrateModelLimitsFromClient(client) {
5148
5240
  return this.catalog.hydrateFromClient(client);
5149
5241
  }
5150
- // [FIX #346] The init-time seed (above) is fire-and-forget and races
5151
- // server readiness: in headless spawn+resume mode the provider-config
5152
- // call can fail before the server is up, leaving the catalog empty for
5153
- // the process's lifetime. During a request the server is guaranteed up
5154
- // (we are inside its pipeline), so on a catalog miss we retry hydration
5155
- // once per process before giving up (the fallback limit then applies).
5156
- // The in-flight promise (not a boolean) lets concurrent callers await the
5157
- // same hydration instead of skipping it.
5242
+ // Initialization can precede provider readiness. Retry request-time misses,
5243
+ // sharing in-flight work and cooling down completed attempts so an unknown
5244
+ // model cannot cause a catalog request on every turn. Cache hits never wait.
5158
5245
  lazyHydration;
5246
+ nextModelLimitRetryAt = 0;
5159
5247
  async hydrateAndResolve(client, providerId, modelId) {
5160
5248
  const existing = this.catalog.resolve(providerId, modelId);
5161
5249
  if (existing !== void 0) {
5162
5250
  return existing;
5163
5251
  }
5164
- this.lazyHydration ??= this.catalog.hydrateFromClient(client);
5252
+ if (!this.lazyHydration && Date.now() >= this.nextModelLimitRetryAt) {
5253
+ this.lazyHydration = this.catalog.hydrateFromClient(client).finally(() => {
5254
+ this.nextModelLimitRetryAt = Date.now() + MODEL_LIMIT_RETRY_INTERVAL_MS;
5255
+ this.lazyHydration = void 0;
5256
+ });
5257
+ }
5165
5258
  await this.lazyHydration;
5166
- return this.catalog.resolve(providerId, modelId);
5259
+ const limit = this.catalog.resolve(providerId, modelId);
5260
+ this.logger.debug("Model limit catalog lookup", {
5261
+ model: `${providerId}/${modelId}`,
5262
+ reason: limit === void 0 ? "model_not_found" : "model",
5263
+ retryAfterMs: limit === void 0 ? Math.max(0, this.nextModelLimitRetryAt - Date.now()) : 0
5264
+ });
5265
+ return limit;
5167
5266
  }
5168
5267
  get(sessionId) {
5169
5268
  return this.states.get(sessionId);
@@ -5266,6 +5365,7 @@ function createSessionState() {
5266
5365
  }
5267
5366
  function resetSessionState(state) {
5268
5367
  state.sessionId = null;
5368
+ state.visibleHostInputIds = void 0;
5269
5369
  state.isSubAgent = false;
5270
5370
  state.compressPermission = void 0;
5271
5371
  state.prune = {
@@ -5517,7 +5617,7 @@ function cacheSystemPromptTokens(state, messages) {
5517
5617
  }
5518
5618
  let firstUserText = "";
5519
5619
  for (const msg of messages) {
5520
- if (msg.info.role !== "user" || isIgnoredUserMessage(msg)) {
5620
+ if (!isUserPrompt(msg)) {
5521
5621
  continue;
5522
5622
  }
5523
5623
  const parts = Array.isArray(msg.parts) ? msg.parts : [];
@@ -5740,7 +5840,8 @@ ${message}`);
5740
5840
  await client.session.synthetic({
5741
5841
  sessionID: sessionId,
5742
5842
  text: toastMessage,
5743
- description: "ACP: Compress Notification"
5843
+ description: "ACP: Compress Notification",
5844
+ metadata: { source: "opencode-acp" }
5744
5845
  });
5745
5846
  return true;
5746
5847
  }
@@ -5749,7 +5850,8 @@ async function sendIgnoredMessage(client, sessionID, text, params, logger) {
5749
5850
  await client.session.synthetic({
5750
5851
  sessionID,
5751
5852
  text,
5752
- description: "ACP"
5853
+ description: "ACP",
5854
+ metadata: { source: "opencode-acp" }
5753
5855
  });
5754
5856
  } catch (error) {
5755
5857
  logger.error("Failed to send notification", { error: error.message });
@@ -6604,9 +6706,14 @@ function restoreCompressionState(state, snapshot) {
6604
6706
  state.prune.messages = structuredClone(snapshot.messages);
6605
6707
  state.stats = { ...snapshot.stats };
6606
6708
  }
6709
+ function filterUnseenHostInputs(state, messages) {
6710
+ return messages.filter(
6711
+ (message) => !isHostInput(message) || state.visibleHostInputIds?.has(message.info.id) === true || (state.prune.messages.byMessageId.get(message.info.id)?.activeBlockIds.length ?? 0) > 0
6712
+ );
6713
+ }
6607
6714
  async function prepareSession(ctx, toolCtx, title) {
6608
6715
  await ctx.assertPermission(toolCtx.sessionID);
6609
- const rawMessages = await fetchSessionMessages(ctx.client, toolCtx.sessionID);
6716
+ let rawMessages = await fetchSessionMessages(ctx.client, toolCtx.sessionID);
6610
6717
  await ensureSessionInitialized(
6611
6718
  ctx.client,
6612
6719
  ctx.state,
@@ -6615,6 +6722,7 @@ async function prepareSession(ctx, toolCtx, title) {
6615
6722
  rawMessages,
6616
6723
  ctx.config
6617
6724
  );
6725
+ rawMessages = filterUnseenHostInputs(ctx.state, rawMessages);
6618
6726
  assignMessageRefs(ctx.state, rawMessages);
6619
6727
  return {
6620
6728
  rawMessages,
@@ -7321,7 +7429,7 @@ function countMessagesAfterIndex(messages, index) {
7321
7429
  return count;
7322
7430
  }
7323
7431
  function getModelInfo(messages) {
7324
- const lastUserMessage = getLastUserMessage(messages);
7432
+ const lastUserMessage = getRequestInput(messages);
7325
7433
  if (!lastUserMessage) {
7326
7434
  return {
7327
7435
  providerId: void 0,
@@ -7542,7 +7650,7 @@ function collectTurnNudgeAnchors2(state, config, messages) {
7542
7650
  const targetRole = config.compress.nudgeForce === "strong" ? "user" : "assistant";
7543
7651
  for (const message of messages) {
7544
7652
  if (!state.nudges.turnNudgeAnchors.has(message.info.id)) continue;
7545
- if (message.info.role === targetRole) {
7653
+ if (targetRole === "user" ? isUserPrompt(message) : message.info.role === targetRole) {
7546
7654
  turnNudgeAnchors.add(message.info.id);
7547
7655
  }
7548
7656
  }
@@ -7716,7 +7824,6 @@ function buildCompressibleRanges(messages, state, protectedTools = [], protected
7716
7824
  if (isSyntheticMessage(msg)) continue;
7717
7825
  const ref = state.messageIds.byRawId.get(msg.info.id);
7718
7826
  if (!ref) continue;
7719
- const rn = parseInt(ref.slice(1), 10);
7720
7827
  if ((protectedTools.length > 0 || protectedFilePatterns.length > 0) && messageContainsProtectedTool(msg, protectedTools, protectedFilePatterns)) {
7721
7828
  const tokens2 = Math.round(countMessageCharacters(msg) / 4);
7722
7829
  const tools = /* @__PURE__ */ new Set();
@@ -7739,7 +7846,7 @@ function buildCompressibleRanges(messages, state, protectedTools = [], protected
7739
7846
  }
7740
7847
  }
7741
7848
  }
7742
- protectedMsgInfo.push({ ref, refNum: rn, tokens: tokens2, tools: [...tools] });
7849
+ protectedMsgInfo.push({ ref, rawIndex: mi, tokens: tokens2, tools: [...tools] });
7743
7850
  continue;
7744
7851
  }
7745
7852
  const tokens = Math.round(countMessageCharacters(msg) / 4);
@@ -7753,18 +7860,18 @@ function buildCompressibleRanges(messages, state, protectedTools = [], protected
7753
7860
  hasMeaningfulPart = true;
7754
7861
  }
7755
7862
  }
7756
- if (msg.info.role === "user" && !isIgnoredUserMessage(msg)) {
7863
+ if (isUserPrompt(msg)) {
7757
7864
  lastUserRefIdx.length = 0;
7758
7865
  lastUserRefIdx.push(msgInfo.length);
7759
7866
  }
7760
7867
  msgInfo.push({
7761
7868
  ref,
7762
- refNum: rn,
7869
+ rawIndex: mi,
7763
7870
  tokens,
7764
7871
  effectiveTokens: 0,
7765
7872
  meaningful: hasMeaningfulPart,
7766
7873
  isTool,
7767
- isUser: msg.info.role === "user"
7874
+ isUser: isUserPrompt(msg)
7768
7875
  });
7769
7876
  }
7770
7877
  const lastUserIdx = lastUserRefIdx.length > 0 ? lastUserRefIdx[0] : -1;
@@ -7774,26 +7881,28 @@ function buildCompressibleRanges(messages, state, protectedTools = [], protected
7774
7881
  }
7775
7882
  const groups = [];
7776
7883
  let cur = null;
7777
- let prevRefNum = -2;
7884
+ let previousIndex = -2;
7778
7885
  for (const info of msgInfo) {
7779
7886
  if (protectedZoneRefs?.has(info.ref)) {
7780
7887
  if (cur) {
7781
7888
  groups.push(cur);
7782
7889
  cur = null;
7783
7890
  }
7784
- prevRefNum = info.refNum;
7891
+ previousIndex = info.rawIndex;
7785
7892
  continue;
7786
7893
  }
7787
- const hasGap = info.refNum !== prevRefNum + 1;
7894
+ const hasGap = info.rawIndex !== previousIndex + 1;
7788
7895
  if (cur && (info.isUser && cur.count >= 3 || hasGap)) {
7789
7896
  groups.push(cur);
7790
7897
  cur = null;
7791
7898
  }
7792
- prevRefNum = info.refNum;
7899
+ previousIndex = info.rawIndex;
7793
7900
  if (!cur) {
7794
7901
  cur = {
7795
7902
  startRef: info.ref,
7796
7903
  endRef: info.ref,
7904
+ startIndex: info.rawIndex,
7905
+ endIndex: info.rawIndex,
7797
7906
  count: 1,
7798
7907
  tokens: info.tokens,
7799
7908
  effectiveTokens: info.effectiveTokens,
@@ -7802,6 +7911,7 @@ function buildCompressibleRanges(messages, state, protectedTools = [], protected
7802
7911
  };
7803
7912
  } else {
7804
7913
  cur.endRef = info.ref;
7914
+ cur.endIndex = info.rawIndex;
7805
7915
  cur.count++;
7806
7916
  cur.tokens += info.tokens;
7807
7917
  cur.effectiveTokens += info.effectiveTokens;
@@ -7816,24 +7926,27 @@ function buildCompressibleRanges(messages, state, protectedTools = [], protected
7816
7926
  if (cur) groups.push(cur);
7817
7927
  const protectedGroups = [];
7818
7928
  let pcur = null;
7819
- let pPrevRefNum = -2;
7929
+ let previousProtectedIndex = -2;
7820
7930
  for (const info of protectedMsgInfo) {
7821
- const hasGap = info.refNum > pPrevRefNum + 1;
7931
+ const hasGap = info.rawIndex !== previousProtectedIndex + 1;
7822
7932
  if (pcur && hasGap) {
7823
7933
  protectedGroups.push(pcur);
7824
7934
  pcur = null;
7825
7935
  }
7826
- pPrevRefNum = info.refNum;
7936
+ previousProtectedIndex = info.rawIndex;
7827
7937
  if (!pcur) {
7828
7938
  pcur = {
7829
7939
  startRef: info.ref,
7830
7940
  endRef: info.ref,
7941
+ startIndex: info.rawIndex,
7942
+ endIndex: info.rawIndex,
7831
7943
  count: 1,
7832
7944
  tokens: info.tokens,
7833
7945
  tools: [...info.tools]
7834
7946
  };
7835
7947
  } else {
7836
7948
  pcur.endRef = info.ref;
7949
+ pcur.endIndex = info.rawIndex;
7837
7950
  pcur.count++;
7838
7951
  pcur.tokens += info.tokens;
7839
7952
  for (const t of info.tools) {
@@ -7894,8 +8007,8 @@ ${lines2.join("\n")}`;
7894
8007
  entries.push({
7895
8008
  startRef: r.startRef,
7896
8009
  endRef: r.endRef,
7897
- startNum: refNum(r.startRef),
7898
- endNum: refNum(r.endRef),
8010
+ startIndex: r.startIndex,
8011
+ endIndex: r.endIndex,
7899
8012
  count: r.count,
7900
8013
  tokens: r.tokens,
7901
8014
  toolPct: r.toolPct,
@@ -7912,8 +8025,8 @@ ${lines2.join("\n")}`;
7912
8025
  entries.push({
7913
8026
  startRef: r.startRef,
7914
8027
  endRef: r.endRef,
7915
- startNum: refNum(r.startRef),
7916
- endNum: refNum(r.endRef),
8028
+ startIndex: r.startIndex,
8029
+ endIndex: r.endIndex,
7917
8030
  count: r.count,
7918
8031
  tokens: r.tokens,
7919
8032
  toolPct: 0,
@@ -7926,13 +8039,15 @@ ${lines2.join("\n")}`;
7926
8039
  dangerous: false
7927
8040
  });
7928
8041
  }
7929
- entries.sort((a, b) => a.startNum - b.startNum);
8042
+ entries.sort(
8043
+ (a, b) => (a.startIndex ?? refNum(a.startRef)) - (b.startIndex ?? refNum(b.startRef))
8044
+ );
7930
8045
  const merged = [];
7931
8046
  for (const entry of entries) {
7932
8047
  const last = merged[merged.length - 1];
7933
- if (last && entry.startNum <= last.endNum + 1) {
8048
+ if (last && last.endIndex !== void 0 && entry.startIndex === last.endIndex + 1 && last.protectedCount > 0 === entry.protectedCount > 0) {
7934
8049
  last.endRef = entry.endRef;
7935
- last.endNum = Math.max(last.endNum, entry.endNum);
8050
+ last.endIndex = entry.endIndex;
7936
8051
  last.count += entry.count;
7937
8052
  last.tokens += entry.tokens;
7938
8053
  last.compressibleTokens += entry.compressibleTokens;
@@ -7980,7 +8095,7 @@ function computeProtectedRefs(messages, state, compress) {
7980
8095
  tokens += Math.round(JSON.stringify(part).length / 4);
7981
8096
  }
7982
8097
  }
7983
- visible.push({ ref, tokens, isUser: msg.info.role === "user" });
8098
+ visible.push({ ref, tokens, isUser: isUserPrompt(msg) });
7984
8099
  }
7985
8100
  if (preserveN > 0) {
7986
8101
  for (const m of visible.slice(-preserveN)) {
@@ -8005,15 +8120,15 @@ function excludeProtectedRanges(ranges, protectedRefs) {
8005
8120
  var SMART_PLAN_TTL_MS = 10 * 60 * 1e3;
8006
8121
  var armedPlans = /* @__PURE__ */ new Map();
8007
8122
  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) {
8123
+ function mergeAdjacentSafeRanges(ranges, searchContext, ctx) {
8013
8124
  const merged = [];
8014
8125
  for (const range of ranges.filter((candidate) => !candidate.dangerous)) {
8015
8126
  const previous = merged.at(-1);
8016
- if (previous && refNumber(range.startRef) === refNumber(previous.endRef) + 1) {
8127
+ const startId = ctx.state.messageIds.byRef.get(range.startRef);
8128
+ const previousEndId = previous && ctx.state.messageIds.byRef.get(previous.endRef);
8129
+ const startIndex = startId && searchContext.rawIndexById.get(startId);
8130
+ const previousEndIndex = previousEndId && searchContext.rawIndexById.get(previousEndId);
8131
+ if (previous && typeof startIndex === "number" && typeof previousEndIndex === "number" && startIndex === previousEndIndex + 1) {
8017
8132
  const previousEffective = previous.effectiveTokens ?? previous.tokens;
8018
8133
  previous.endRef = range.endRef;
8019
8134
  previous.count += range.count;
@@ -8069,7 +8184,7 @@ function filteredSelection(startId, endId, searchContext, ctx) {
8069
8184
  }
8070
8185
  function armBestSmartPlan(sessionID, ranges, searchContext, ctx, visibleMessageIds, now = Date.now(), targetChars = ctx.config.compress.minCompressRange) {
8071
8186
  const candidates = [];
8072
- for (const range of mergeAdjacentSafeRanges(ranges)) {
8187
+ for (const range of mergeAdjacentSafeRanges(ranges, searchContext, ctx)) {
8073
8188
  const selection = filteredSelection(range.startRef, range.endRef, searchContext, ctx);
8074
8189
  if (!selection || selection.messageIds.length === 0) continue;
8075
8190
  if (visibleMessageIds && !selection.messageIds.every((id) => visibleMessageIds.has(id)))
@@ -8456,6 +8571,7 @@ function createCompressRangeTool(factoryCtx) {
8456
8571
  \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
8572
  ` : "";
8458
8573
  return {
8574
+ metadata: { acpHostInputRefs: true },
8459
8575
  content: `Compressed ${totalCompressedMessages} messages into ${COMPRESSED_BLOCK_HEADER}.${skippedNote}${ackNote}
8460
8576
  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
8577
  \u{1F4A1} Tip: Use acp_search_context('keyword') to find compressed content when you need it later.`
@@ -8520,7 +8636,7 @@ var filterCompressedRanges = (state, messages) => {
8520
8636
  }
8521
8637
  return false;
8522
8638
  });
8523
- const firstUserIdx = messages.findIndex((msg) => msg.info.role === "user");
8639
+ const firstUserIdx = messages.findIndex(isUserPrompt);
8524
8640
  if (firstUserIdx >= 0) {
8525
8641
  survive[firstUserIdx] = true;
8526
8642
  }
@@ -8530,6 +8646,20 @@ var filterCompressedRanges = (state, messages) => {
8530
8646
  result.push(messages[i]);
8531
8647
  }
8532
8648
  }
8649
+ if (!result.some((message) => message.info.role === "user")) {
8650
+ const compressedHostInput = messages.find(
8651
+ (message, index) => !survive[index] && isHostInput(message)
8652
+ );
8653
+ if (compressedHostInput) {
8654
+ result.unshift(
8655
+ createSyntheticUserMessage(
8656
+ compressedHostInput,
8657
+ "Earlier host input has been compressed.",
8658
+ "acp-compressed-host-input"
8659
+ )
8660
+ );
8661
+ }
8662
+ }
8533
8663
  messages.length = 0;
8534
8664
  messages.push(...result);
8535
8665
  };
@@ -9328,9 +9458,7 @@ var injectCompressNudges = (state, config, logger, messages, prompts, compressio
9328
9458
  modelId,
9329
9459
  messages
9330
9460
  );
9331
- const lastUserIdx = messages.findLastIndex(
9332
- (m) => m.info.role === "user" && !isIgnoredUserMessage(m)
9333
- );
9461
+ const lastUserIdx = messages.findLastIndex(isUserPrompt);
9334
9462
  const currentTurnStart = lastUserIdx >= 0 ? lastUserIdx + 1 : 0;
9335
9463
  const currentTurnHasCompress = messages.slice(currentTurnStart).some((m) => m.info.role === "assistant" && messageHasCompressAttempt(m));
9336
9464
  if (currentTurnHasCompress) {
@@ -9410,7 +9538,7 @@ var injectCompressNudges = (state, config, logger, messages, prompts, compressio
9410
9538
  anchorsChanged = true;
9411
9539
  }
9412
9540
  if (overMinLimit) {
9413
- const isLastMessageUser = lastMessage?.message.info.role === "user";
9541
+ const isLastMessageUser = lastMessage && isUserPrompt(lastMessage.message);
9414
9542
  if (isLastMessageUser && lastAssistantMessage) {
9415
9543
  const previousSize = state.nudges.turnNudgeAnchors.size;
9416
9544
  state.nudges.turnNudgeAnchors.add(lastMessage.message.info.id);
@@ -11206,7 +11334,10 @@ function createAcpStatusToolV2(factoryCtx) {
11206
11334
  }
11207
11335
  let rawMessages = [];
11208
11336
  try {
11209
- rawMessages = await fetchSessionMessages(ctx.client, toolCtx.sessionID);
11337
+ rawMessages = filterUnseenHostInputs(
11338
+ ctx.state,
11339
+ await fetchSessionMessages(ctx.client, toolCtx.sessionID)
11340
+ );
11210
11341
  } catch {
11211
11342
  if (scope === "uncompressed") return { content: "(unable to fetch messages)" };
11212
11343
  }
@@ -11415,7 +11546,7 @@ import { writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
11415
11546
  import { join as join5 } from "path";
11416
11547
  import { existsSync as existsSync5 } from "fs";
11417
11548
  import { homedir as homedir3 } from "os";
11418
- var LOG_VERSION = true ? "2.0.0-alpha.7" : "dev";
11549
+ var LOG_VERSION = true ? "2.0.0-alpha.9" : "dev";
11419
11550
  var LEVEL_RANK = {
11420
11551
  debug: 10,
11421
11552
  info: 20,
@@ -13213,11 +13344,11 @@ function runBatchCleanup(state, config, logger, messages, prePruneTokens) {
13213
13344
  // src/v2/hooks/messages.ts
13214
13345
  var INTERNAL_AGENT_NAMES = /* @__PURE__ */ new Set(["title", "summary", "compaction"]);
13215
13346
  function isInternalAgentRequest(messages) {
13216
- const lastUserMessage = getLastUserMessage(messages);
13217
- if (!lastUserMessage) {
13347
+ const requestInput = getRequestInput(messages);
13348
+ if (!requestInput) {
13218
13349
  return false;
13219
13350
  }
13220
- const agent = lastUserMessage.info.agent;
13351
+ const agent = requestInput.info.agent;
13221
13352
  return typeof agent === "string" && INTERNAL_AGENT_NAMES.has(agent);
13222
13353
  }
13223
13354
  function createChatMessageTransformHandler(client, registry4, logger, config, prompts, hostPermissions) {
@@ -13240,19 +13371,19 @@ function createChatMessageTransformHandler(client, registry4, logger, config, pr
13240
13371
  return;
13241
13372
  }
13242
13373
  checkpoint("resolveSession");
13243
- const lastUserMessage = getLastUserMessage(messages);
13374
+ const requestInput = getRequestInput(messages);
13244
13375
  let state;
13245
- if (!lastUserMessage) {
13376
+ if (!requestInput) {
13246
13377
  state = createSessionState();
13247
13378
  } else {
13248
13379
  state = await registry4.getOrCreate(
13249
13380
  client,
13250
- lastUserMessage.info.sessionID,
13381
+ requestInput.info.sessionID,
13251
13382
  messages,
13252
13383
  config
13253
13384
  );
13254
13385
  checkpoint("resolveModel");
13255
- const requestModel = lastUserMessage.info.model;
13386
+ const requestModel = requestInput.info.model;
13256
13387
  let requestModelLimit = registry4.resolveModelLimit(
13257
13388
  requestModel?.providerID,
13258
13389
  requestModel?.modelID
@@ -13297,11 +13428,14 @@ function createChatMessageTransformHandler(client, registry4, logger, config, pr
13297
13428
  checkpoint("permissions");
13298
13429
  if (state.modelContextLimit === void 0 && !state.noContextLimitWarned && requestModel?.providerID && requestModel?.modelID && registry4.resolveModelLimit(requestModel.providerID, requestModel.modelID) === void 0) {
13299
13430
  state.noContextLimitWarned = true;
13431
+ const effectiveLimit2 = resolveEffectiveContextLimit(state, config);
13300
13432
  logger.warn(
13301
- 'Model reports no context window and the catalog has no entry for it; all percentage thresholds (min/max/emergency, GC) and the context-budget guard are disabled. Set the model limit in opencode.json (e.g. "limit": {"context": 262144, "output": 16384}) to enable them (also fixes the 32000 max_tokens fallback); an absolute compress.maxContextLimit in acp.jsonc only enables proactive nudges, not the guard.',
13433
+ effectiveLimit2 ? "Model context window is unavailable in the catalog; using compress.contextLimitFallback. A smaller fallback may trigger compression early; a larger one may overestimate the available budget. Check the provider/model limit in OpenCode and the model catalog load logs. Catalog misses are retried on later requests with a cooldown." : "Model context window is unavailable in the catalog and compress.contextLimitFallback is disabled; checks that require a context window cannot run. Absolute compress.maxContextLimit can still trigger proactive nudges. Check the provider/model limit in OpenCode and the model catalog load logs. Catalog misses are retried on later requests with a cooldown.",
13302
13434
  {
13303
13435
  session: state.sessionId,
13304
- model: `${requestModel.providerID}/${requestModel.modelID}`
13436
+ model: `${requestModel.providerID}/${requestModel.modelID}`,
13437
+ contextLimit: effectiveLimit2?.limit ?? 0,
13438
+ contextLimitSource: effectiveLimit2?.source ?? "unknown"
13305
13439
  }
13306
13440
  );
13307
13441
  }
@@ -13319,7 +13453,7 @@ function createChatMessageTransformHandler(client, registry4, logger, config, pr
13319
13453
  checkpoint("stripHallucinations");
13320
13454
  stripHallucinations(output.messages);
13321
13455
  checkpoint("dropReasoning");
13322
- const dropReasoningModel = lastUserMessage?.info?.model;
13456
+ const dropReasoningModel = requestInput?.info?.model;
13323
13457
  const reasoningConfig = applyCompressOverrides(
13324
13458
  config,
13325
13459
  dropReasoningModel?.providerID ?? state.modelProviderID,
@@ -13550,7 +13684,7 @@ function analyzeTokens(state, messages) {
13550
13684
  const isCompacted = isMessageCompacted(state, msg);
13551
13685
  const pruneEntry = state.prune.messages.byMessageId.get(msg.info.id);
13552
13686
  const isMessagePruned = !!pruneEntry && pruneEntry.activeBlockIds.length > 0;
13553
- const isIgnoredUser = isIgnoredUserMessage(msg);
13687
+ const isHumanPrompt = isUserPrompt(msg);
13554
13688
  for (const part of parts) {
13555
13689
  if (part.type === "tool") {
13556
13690
  const toolPart = part;
@@ -13573,7 +13707,7 @@ function analyzeTokens(state, messages) {
13573
13707
  toolOutputParts.push(outputStr);
13574
13708
  }
13575
13709
  }
13576
- } else if (part.type === "text" && msg.info.role === "user" && !isCompacted && !isIgnoredUser) {
13710
+ } else if (part.type === "text" && isHumanPrompt && !isCompacted) {
13577
13711
  const textPart = part;
13578
13712
  const text = textPart.text || "";
13579
13713
  userTextParts.push(text);
@@ -13582,7 +13716,7 @@ function analyzeTokens(state, messages) {
13582
13716
  }
13583
13717
  }
13584
13718
  }
13585
- if (msg.info.role === "user" && !isIgnoredUser && !foundFirstUser) {
13719
+ if (isHumanPrompt && !foundFirstUser) {
13586
13720
  foundFirstUser = true;
13587
13721
  }
13588
13722
  }
@@ -14350,7 +14484,12 @@ async function notifySession(ctx, title, message) {
14350
14484
  const sessions = Array.isArray(response) ? response : response.data ?? [];
14351
14485
  const sessionID = Array.isArray(sessions) && typeof sessions[0]?.id === "string" ? sessions[0].id : void 0;
14352
14486
  if (sessionID) {
14353
- await ctx.session.synthetic({ sessionID, text: message, description: title });
14487
+ await ctx.session.synthetic({
14488
+ sessionID,
14489
+ text: message,
14490
+ description: title,
14491
+ metadata: { source: "opencode-acp" }
14492
+ });
14354
14493
  }
14355
14494
  } catch {
14356
14495
  }
@@ -14460,14 +14599,14 @@ var AcpV2Plugin = Plugin.define({
14460
14599
  await diagnoseContext(logger, event.sessionID, async (diagnostic) => {
14461
14600
  const timeline = diagnostic?.timeline("context", "fetchSessionMessages");
14462
14601
  const checkpoint = (stage) => timeline?.next(stage);
14463
- const messages = await fetchV2SessionMessages(ctx, event.sessionID);
14602
+ const messages = await fetchV2SessionMessages(ctx, event.sessionID, event.messages);
14464
14603
  checkpoint("prepareMessages");
14465
14604
  if (diagnostic) diagnostic.counts.inputMessages = messages.length;
14466
14605
  if (messages.length === 0) {
14467
14606
  diagnostic?.skip("empty_history");
14468
14607
  return;
14469
14608
  }
14470
- const lastUser = [...messages].reverse().find((message) => message.info.role === "user");
14609
+ const lastUser = getRequestInput(messages);
14471
14610
  if (lastUser?.info.role === "user") {
14472
14611
  lastUser.info.agent = event.agent;
14473
14612
  lastUser.info.model = {
@@ -14483,6 +14622,12 @@ var AcpV2Plugin = Plugin.define({
14483
14622
  if (diagnostic) diagnostic.counts.outputMessages = output.messages.length;
14484
14623
  checkpoint("convertRequestMessages");
14485
14624
  event.messages = toV2RequestMessages(output.messages);
14625
+ const state = registry4.get(event.sessionID);
14626
+ if (state) {
14627
+ state.visibleHostInputIds = new Set(
14628
+ output.messages.filter(isHostInput).map((message) => message.info.id)
14629
+ );
14630
+ }
14486
14631
  checkpoint("transformSystem");
14487
14632
  const systemOutput = {
14488
14633
  system: event.system.map((part) => part.text)