@retaw106/mmc-pi 2.1.1 → 2.2.0

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/cli.js CHANGED
@@ -5023,7 +5023,6 @@ var HistorianConfigSchema = AgentMetadataSchema.extend({
5023
5023
  var MagicContextConfigSchema = object({
5024
5024
  enabled: boolean2().default(true).describe("Enable magic context (default: true)"),
5025
5025
  allow_home_project: boolean2().default(false).describe("Allow Magic Context sessions launched from the exact canonical home directory. A non-git home uses its deterministic dir: identity; a home repository uses its git: identity. USER-LEVEL ONLY: project config is ignored. The home identity is excluded from registry seed exports, never resolves descendants by containment, and cannot join a workspace."),
5026
- auto_update: boolean2().optional().describe("DEPRECATED no-op: the automatic update check was removed (the package is private-registry-only, so public npm checks always 404). The key is still accepted so existing configs keep parsing; upgrade via the host's own plugin update channel."),
5027
5026
  language: string2().trim().toLowerCase().refine((s) => isValidLanguageCode(s), 'language must be a 2-letter ISO 639-1 code (e.g. "tr", "es", "de")').optional().describe("Output language for Magic Context's generated content and guidance, as a " + '2-letter ISO 639-1 code (e.g. "tr", "es", "de", "ja", "pt"). When set, the ' + "historian and the agent-guidance block instruct the model to " + "write its PROSE in this language while keeping all structural tokens (XML tags, " + "the five memory category names, code identifiers, file paths) in English. " + "USER-LEVEL ONLY (ignored in project config for security). Unset = today's " + "behavior (model mirrors the conversation; English scaffolding). Changing it " + "triggers one cache re-materialization; existing compartments/memories keep their " + "original language until naturally rewritten."),
5028
5027
  profile: string2().trim().min(1).optional().describe("Select a named user-owned model profile. A valid project name overrides this user default; an empty string, null, or other non-string project value is ignored with a warning so the user selection still applies. Unknown names warn and use the base configuration."),
5029
5028
  profiles: ConfigProfilesSchema.optional().describe("User-level named model profiles. A profile may contain only the flat historian model-resolution fields (model, fallback_models, OpenCode variant, Pi thinking_level). Project configs may select a name but cannot define profiles."),
@@ -5040,7 +5040,6 @@ var HistorianConfigSchema = AgentMetadataSchema.extend({
5040
5040
  var MagicContextConfigSchema = object({
5041
5041
  enabled: boolean2().default(true).describe("Enable magic context (default: true)"),
5042
5042
  allow_home_project: boolean2().default(false).describe("Allow Magic Context sessions launched from the exact canonical home directory. A non-git home uses its deterministic dir: identity; a home repository uses its git: identity. USER-LEVEL ONLY: project config is ignored. The home identity is excluded from registry seed exports, never resolves descendants by containment, and cannot join a workspace."),
5043
- auto_update: boolean2().optional().describe("DEPRECATED no-op: the automatic update check was removed (the package is private-registry-only, so public npm checks always 404). The key is still accepted so existing configs keep parsing; upgrade via the host's own plugin update channel."),
5044
5043
  language: string2().trim().toLowerCase().refine((s) => isValidLanguageCode(s), 'language must be a 2-letter ISO 639-1 code (e.g. "tr", "es", "de")').optional().describe("Output language for Magic Context's generated content and guidance, as a " + '2-letter ISO 639-1 code (e.g. "tr", "es", "de", "ja", "pt"). When set, the ' + "historian and the agent-guidance block instruct the model to " + "write its PROSE in this language while keeping all structural tokens (XML tags, " + "the five memory category names, code identifiers, file paths) in English. " + "USER-LEVEL ONLY (ignored in project config for security). Unset = today's " + "behavior (model mirrors the conversation; English scaffolding). Changing it " + "triggers one cache re-materialization; existing compartments/memories keep their " + "original language until naturally rewritten."),
5045
5044
  profile: string2().trim().min(1).optional().describe("Select a named user-owned model profile. A valid project name overrides this user default; an empty string, null, or other non-string project value is ignored with a warning so the user selection still applies. Unknown names warn and use the base configuration."),
5046
5045
  profiles: ConfigProfilesSchema.optional().describe("User-level named model profiles. A profile may contain only the flat historian model-resolution fields (model, fallback_models, OpenCode variant, Pi thinking_level). Project configs may select a name but cannot define profiles."),
@@ -539,6 +539,11 @@ function mergeProtectedTools(...maps) {
539
539
 
540
540
  // ../plugin/src/features/magic-context/reclaim-protection.ts
541
541
  var CTX_REDUCE_KEEP = DEFAULT_PROTECTED_TOOLS.mmc_reduce;
542
+ function adoptedProtectedToolsPolicy(current, previous, rebuilding, hasBaseline) {
543
+ if (rebuilding || !hasBaseline)
544
+ return mergeProtectedTools(current);
545
+ return { ...previous ?? { todowrite: 0, mmc_reduce: 3 } };
546
+ }
542
547
  function protectedToolTagNumbers(tags, protectedTools) {
543
548
  const counts = mergeProtectedTools(protectedTools);
544
549
  const protectedTags = new Set;
@@ -1037,6 +1042,17 @@ function stableStringify(value, seen = new WeakSet) {
1037
1042
 
1038
1043
  // ../plugin/src/shared/tag-owner-id.ts
1039
1044
  var TEXT_TAG_IDENTITY_MARKER = ":mc-text-v1:";
1045
+ var POSITIONAL_CONTENT_SUFFIX = /:(?:p|file)\d+$/;
1046
+ var CONTENT_DERIVED_TEXT_SUFFIX = /:mc-text-v1:[0-9a-f]+:[0-9a-f]+:o\d+$/;
1047
+ function contentTagOwnerMessageId(contentId) {
1048
+ const positional = POSITIONAL_CONTENT_SUFFIX.exec(contentId);
1049
+ if (positional)
1050
+ return contentId.slice(0, positional.index);
1051
+ const derived = CONTENT_DERIVED_TEXT_SUFFIX.exec(contentId);
1052
+ if (derived)
1053
+ return contentId.slice(0, derived.index);
1054
+ return contentId;
1055
+ }
1040
1056
 
1041
1057
  // ../plugin/src/hooks/magic-context/image-token-estimate.ts
1042
1058
  var IMAGE_TOKEN_DIVISOR = 750;
@@ -2033,14 +2049,13 @@ function getUpdateTagInputByteSizeStatement(db) {
2033
2049
  function updateTagByteSize(db, sessionId, tagNumber, newByteSize) {
2034
2050
  getUpdateTagByteSizeStatement(db).run(newByteSize, sessionId, tagNumber);
2035
2051
  }
2036
- var CONTENT_ID_SUFFIX = /:(?:p|file)\d+$/;
2037
2052
  var RECENT_OWNER_SCAN_PAGE_SIZE = 128;
2038
2053
  var recentTagOwnerStatements = new WeakMap;
2039
2054
  function ownerMessageIdForTagRow(row) {
2040
2055
  if (row.type === "tool") {
2041
2056
  return row.tool_owner_message_id ?? row.message_id;
2042
2057
  }
2043
- return row.message_id.replace(CONTENT_ID_SUFFIX, "");
2058
+ return contentTagOwnerMessageId(row.message_id);
2044
2059
  }
2045
2060
  function getRecentTagOwnerStatement(db) {
2046
2061
  let statement = recentTagOwnerStatements.get(db);
@@ -2065,7 +2080,7 @@ function getRecentTagOwnerMessageIds(db, sessionId, maxOwners) {
2065
2080
  for (const row of rows) {
2066
2081
  if (typeof row.type !== "string" || typeof row.message_id !== "string")
2067
2082
  continue;
2068
- const ownerId = row.type === "tool" ? typeof row.tool_owner_message_id === "string" ? row.tool_owner_message_id : null : row.message_id.replace(CONTENT_ID_SUFFIX, "");
2083
+ const ownerId = row.type === "tool" ? typeof row.tool_owner_message_id === "string" ? row.tool_owner_message_id : null : contentTagOwnerMessageId(row.message_id);
2069
2084
  if (!ownerId || recent.has(ownerId))
2070
2085
  continue;
2071
2086
  recent.add(ownerId);
@@ -4083,6 +4098,8 @@ function estimateNonToolPart(part, options, breakdown) {
4083
4098
  addBreakdown(breakdown, "reasoning", estimateTokens(reasoningText));
4084
4099
  return true;
4085
4100
  }
4101
+ if (type === "media" && part.mediaType === "application/pdf")
4102
+ return true;
4086
4103
  if (looksImageLike(part)) {
4087
4104
  addBreakdown(breakdown, "image", options.imageTokenHeuristic?.(part) ?? defaultImageTokenHeuristic(part));
4088
4105
  const altText = firstStringField(part, ["alt", "text", "description"]);
@@ -4359,6 +4376,88 @@ function invalidateTrueRawTokenCache(args) {
4359
4376
  args.reason;
4360
4377
  }
4361
4378
 
4379
+ // ../plugin/src/hooks/magic-context/system-injection-stripper.ts
4380
+ var SYSTEM_INJECTION_MARKERS = [
4381
+ "<!-- OMO_INTERNAL_INITIATOR -->",
4382
+ "[SYSTEM DIRECTIVE: MAGIC-CONTEXT",
4383
+ "[SYSTEM DIRECTIVE: OH-MY-OPENCODE",
4384
+ "[Category+Skill Reminder]",
4385
+ "[EDIT ERROR - IMMEDIATE ACTION REQUIRED]",
4386
+ "[task CALL FAILED - IMMEDIATE RETRY REQUIRED]",
4387
+ "[EMERGENCY CONTEXT WINDOW WARNING]",
4388
+ "Unstable background agent appears idle",
4389
+ "**THE SUBAGENT JUST CLAIMED THIS TASK IS DONE."
4390
+ ];
4391
+ var SYSTEM_REMINDER_REGEX = /<system-reminder>[\s\S]*?<\/system-reminder>/gi;
4392
+ var OMO_MARKER_REGEX = /<!-- OMO_INTERNAL_INITIATOR -->/g;
4393
+ var STEERING_WRAPPER_REGEX = /<system-reminder>\nThe user sent the following message:\n[\s\S]*?\n\nPlease address this message and continue with your tasks\.\n<\/system-reminder>/g;
4394
+ function stripSystemInjection(text) {
4395
+ STEERING_WRAPPER_REGEX.lastIndex = 0;
4396
+ if (!STEERING_WRAPPER_REGEX.test(text))
4397
+ return stripInjectedRegions(text);
4398
+ STEERING_WRAPPER_REGEX.lastIndex = 0;
4399
+ let result = "";
4400
+ let changed = false;
4401
+ let cursor = 0;
4402
+ const keepOrStrip = (segment) => {
4403
+ const stripped = stripInjectedRegions(segment);
4404
+ if (stripped === null) {
4405
+ result += segment;
4406
+ } else {
4407
+ result += stripped;
4408
+ changed = true;
4409
+ }
4410
+ };
4411
+ for (const match of text.matchAll(STEERING_WRAPPER_REGEX)) {
4412
+ keepOrStrip(text.slice(cursor, match.index));
4413
+ result += match[0];
4414
+ cursor = match.index + match[0].length;
4415
+ }
4416
+ keepOrStrip(text.slice(cursor));
4417
+ return changed ? result.trim() : null;
4418
+ }
4419
+ function stripOutsideSteeringWrappers(text, strip) {
4420
+ STEERING_WRAPPER_REGEX.lastIndex = 0;
4421
+ let result = "";
4422
+ let cursor = 0;
4423
+ for (const match of text.matchAll(STEERING_WRAPPER_REGEX)) {
4424
+ result += strip(text.slice(cursor, match.index));
4425
+ result += match[0];
4426
+ cursor = match.index + match[0].length;
4427
+ }
4428
+ return result + strip(text.slice(cursor));
4429
+ }
4430
+ function stripInjectedRegions(text) {
4431
+ let hasInjection = false;
4432
+ for (const marker of SYSTEM_INJECTION_MARKERS) {
4433
+ if (text.includes(marker)) {
4434
+ hasInjection = true;
4435
+ break;
4436
+ }
4437
+ }
4438
+ if (SYSTEM_REMINDER_REGEX.test(text))
4439
+ hasInjection = true;
4440
+ SYSTEM_REMINDER_REGEX.lastIndex = 0;
4441
+ if (!hasInjection)
4442
+ return null;
4443
+ let cleaned = text;
4444
+ cleaned = cleaned.replace(SYSTEM_REMINDER_REGEX, "");
4445
+ cleaned = cleaned.replace(OMO_MARKER_REGEX, "");
4446
+ cleaned = cleaned.replace(/\[SYSTEM DIRECTIVE: OH-MY-(?:OPENCODE|CLAUDE)[^\]]*\][\s\S]*?(?=\n\n(?!\s*[-*])|$)/g, "");
4447
+ for (const marker of SYSTEM_INJECTION_MARKERS) {
4448
+ if (marker.startsWith("<!-- ") || marker.startsWith("[SYSTEM DIRECTIVE"))
4449
+ continue;
4450
+ const idx = cleaned.indexOf(marker);
4451
+ if (idx === -1)
4452
+ continue;
4453
+ const blockEnd = cleaned.indexOf(`
4454
+
4455
+ `, idx + marker.length);
4456
+ cleaned = blockEnd !== -1 ? cleaned.slice(0, idx) + cleaned.slice(blockEnd) : cleaned.slice(0, idx);
4457
+ }
4458
+ return cleaned.trim();
4459
+ }
4460
+
4362
4461
  // ../plugin/src/hooks/magic-context/tag-part-guards.ts
4363
4462
  function isTextPart(part) {
4364
4463
  if (part === null || typeof part !== "object")
@@ -4726,6 +4825,10 @@ function detectThinkingBindingMismatch(error) {
4726
4825
  ...firstChangedPath ? { firstChangedPath } : {}
4727
4826
  };
4728
4827
  }
4828
+ function detectLatestTurnThinkingMismatch(error) {
4829
+ const status = extractExplicitHttpStatus(error);
4830
+ return (status === undefined || status === 400) && /(?:thinking|redacted_thinking)[\s\S]*latest assistant (?:message|turn)[\s\S]*cannot be modified/i.test(extractErrorMessage(error));
4831
+ }
4729
4832
  var PREFIX_BOUND_THINKING_MODELS = [
4730
4833
  ["fable", 5, 1],
4731
4834
  ["opus", 5, 5],
@@ -4738,6 +4841,11 @@ function isPrefixBoundThinkingModel(_providerID, modelID) {
4738
4841
  return false;
4739
4842
  return PREFIX_BOUND_THINKING_PATTERN.test(modelID);
4740
4843
  }
4844
+ function isFable51ThinkingBindingModel(providerID, modelID) {
4845
+ if (providerID?.toLowerCase() !== "anthropic" || !modelID)
4846
+ return false;
4847
+ return /(?:^|[-_.])fable[-_.]?5[-_.]1(?:$|[-_.])/i.test(modelID);
4848
+ }
4741
4849
  function detectOverflow(error) {
4742
4850
  const message = extractErrorMessage(error);
4743
4851
  if (!message) {
@@ -4884,7 +4992,7 @@ var VARIANT_CACHE_PRESERVING_MODELS = {
4884
4992
  function canonicalVariantModelIdentity(providerID, modelID) {
4885
4993
  const normalizedProviderID = providerID.toLowerCase();
4886
4994
  const isAnthropicFamily = normalizedProviderID === "anthropic" || normalizedProviderID === "google-vertex-anthropic" || normalizedProviderID.includes("bedrock");
4887
- if (isAnthropicFamily && isPrefixBoundThinkingModel("anthropic", modelID)) {
4995
+ if (isAnthropicFamily && isFable51ThinkingBindingModel("anthropic", modelID)) {
4888
4996
  return "anthropic/claude-fable-5-1";
4889
4997
  }
4890
4998
  return canonicalModelIdentity(`${providerID}/${modelID}`).toLowerCase();
@@ -4976,19 +5084,28 @@ var sessionProviders = new Map;
4976
5084
  function resolveHostServedBoundaryId2(sessionId, messageId) {
4977
5085
  if (messageId.length === 0)
4978
5086
  return messageId;
4979
- return sessionProviders.get(sessionId)?.readServedBoundaryId?.(messageId) ?? messageId;
5087
+ return sessionProviders.get(sessionId)?.provider.readServedBoundaryId?.(messageId) ?? messageId;
4980
5088
  }
4981
5089
  function hasRawMessageProvider2(sessionId) {
4982
5090
  return sessionProviders.has(sessionId);
4983
5091
  }
4984
5092
  function setRawMessageProvider2(sessionId, provider) {
4985
- sessionProviders.set(sessionId, provider);
5093
+ const current = sessionProviders.get(sessionId);
5094
+ const registration = current?.provider === provider ? current : { provider, scopes: 0 };
5095
+ registration.scopes += 1;
5096
+ sessionProviders.set(sessionId, registration);
5097
+ let active = true;
4986
5098
  return () => {
4987
- const current = sessionProviders.get(sessionId);
4988
- if (current === provider)
5099
+ if (!active)
5100
+ return;
5101
+ active = false;
5102
+ registration.scopes -= 1;
5103
+ if (registration.scopes === 0 && sessionProviders.get(sessionId) === registration) {
4989
5104
  sessionProviders.delete(sessionId);
5105
+ }
4990
5106
  };
4991
5107
  }
5108
+ var boundedProviderWrappers = new WeakMap;
4992
5109
  function withRawMessageProvider2(sessionId, provider, fn) {
4993
5110
  const cleanup = setRawMessageProvider2(sessionId, provider);
4994
5111
  let result;
@@ -5004,8 +5121,27 @@ function withRawMessageProvider2(sessionId, provider, fn) {
5004
5121
  cleanup();
5005
5122
  return result;
5006
5123
  }
5124
+ var SYSTEM_REMINDER_BLOCK_REGEX = /<system-reminder>[\s\S]*?<\/system-reminder>/gi;
5007
5125
  function cleanUserText2(text) {
5008
- return removeSystemReminders(text).replace(OMO_INTERNAL_INITIATOR_MARKER, "").trim();
5126
+ return stripOutsideSteeringWrappers(text, (segment) => segment.replace(SYSTEM_REMINDER_BLOCK_REGEX, "").replace(OMO_INTERNAL_INITIATOR_MARKER, "")).trim();
5127
+ }
5128
+ function hasMeaningfulChunkUserText(parts) {
5129
+ for (const part of parts) {
5130
+ if (part === null || typeof part !== "object")
5131
+ continue;
5132
+ const candidate = part;
5133
+ if (candidate.type !== "text" || typeof candidate.text !== "string")
5134
+ continue;
5135
+ if (candidate.ignored === true)
5136
+ continue;
5137
+ const cleaned = cleanUserText2(candidate.text);
5138
+ if (!cleaned)
5139
+ continue;
5140
+ if (isSystemDirective(cleaned))
5141
+ continue;
5142
+ return true;
5143
+ }
5144
+ return false;
5009
5145
  }
5010
5146
  function withRawSessionMessageCache2(fn) {
5011
5147
  const outerCache = activeRawMessageCache;
@@ -5041,7 +5177,7 @@ function readRawSessionMessages2(sessionId) {
5041
5177
  return readRawSessionMessagesFromSource(sessionId);
5042
5178
  }
5043
5179
  function readRawSessionMessagePage2(sessionId, afterOrdinal, limit, finalWatermark, after) {
5044
- const provider = sessionProviders.get(sessionId);
5180
+ const provider = sessionProviders.get(sessionId)?.provider;
5045
5181
  if (provider?.readMessagePage) {
5046
5182
  return provider.readMessagePage(afterOrdinal, limit, finalWatermark, after);
5047
5183
  }
@@ -5053,7 +5189,7 @@ function readRawSessionMessagePage2(sessionId, afterOrdinal, limit, finalWaterma
5053
5189
  return withReadOnlySessionDb((db) => readRawSessionMessagePageFromDb(db, sessionId, afterOrdinal, limit, finalWatermark, after));
5054
5190
  }
5055
5191
  function getRawSessionMessageOrdinalCount2(sessionId) {
5056
- const provider = sessionProviders.get(sessionId);
5192
+ const provider = sessionProviders.get(sessionId)?.provider;
5057
5193
  if (provider) {
5058
5194
  if (provider.getMessageCount)
5059
5195
  return provider.getMessageCount();
@@ -5066,7 +5202,7 @@ function getRawSessionMessageOrdinalCount2(sessionId) {
5066
5202
  }
5067
5203
  var RAW_MESSAGE_RANGE_PAGE_SIZE = 100;
5068
5204
  function readRawSessionMessageRangeFromSource(sessionId, fromOrdinal, toOrdinal) {
5069
- const provider = sessionProviders.get(sessionId);
5205
+ const provider = sessionProviders.get(sessionId)?.provider;
5070
5206
  if (provider?.iterateMessageRange)
5071
5207
  return [...provider.iterateMessageRange(fromOrdinal, toOrdinal)];
5072
5208
  if (provider && !provider.readMessagePage) {
@@ -5103,7 +5239,7 @@ function visitRawSessionMessages2(sessionId, fromOrdinal, toOrdinal, visit, opti
5103
5239
  const to = Math.floor(toOrdinal);
5104
5240
  if (to < from)
5105
5241
  return;
5106
- const provider = sessionProviders.get(sessionId);
5242
+ const provider = sessionProviders.get(sessionId)?.provider;
5107
5243
  if (provider?.iterateMessageRange) {
5108
5244
  for (const message of provider.iterateMessageRange(from, to)) {
5109
5245
  if (!visit(message))
@@ -5180,7 +5316,7 @@ function primeTailRawMessageCache2(args) {
5180
5316
  return false;
5181
5317
  if (lastCompartmentEnd < 1 || !anchorMessageId)
5182
5318
  return false;
5183
- const provider = sessionProviders.get(sessionId);
5319
+ const provider = sessionProviders.get(sessionId)?.provider;
5184
5320
  if (provider) {
5185
5321
  if (!provider.readMessagePage || !provider.getMessageCount)
5186
5322
  return false;
@@ -5232,7 +5368,7 @@ function readRawSessionMessageIdOrdinalsForRange2(sessionId, fromOrdinal, toOrdi
5232
5368
  const to = Math.floor(toOrdinal);
5233
5369
  if (to < from)
5234
5370
  return new Map;
5235
- const provider = sessionProviders.get(sessionId);
5371
+ const provider = sessionProviders.get(sessionId)?.provider;
5236
5372
  if (provider?.readMessageIdOrdinalsForRange) {
5237
5373
  return provider.readMessageIdOrdinalsForRange(from, to);
5238
5374
  }
@@ -5243,7 +5379,7 @@ function readRawSessionMessageIdOrdinalsForRange2(sessionId, fromOrdinal, toOrdi
5243
5379
  return new Map([...all].filter(([, ordinal]) => ordinal >= from && ordinal <= to));
5244
5380
  }
5245
5381
  function hasRawSessionMessageById2(sessionId, messageId) {
5246
- const provider = sessionProviders.get(sessionId);
5382
+ const provider = sessionProviders.get(sessionId)?.provider;
5247
5383
  if (provider?.hasMessageById)
5248
5384
  return provider.hasMessageById(messageId);
5249
5385
  if (!provider)
@@ -5251,7 +5387,7 @@ function hasRawSessionMessageById2(sessionId, messageId) {
5251
5387
  return readRawSessionMessageById2(sessionId, messageId) !== null;
5252
5388
  }
5253
5389
  function readRawSessionMessageOrdinalById2(sessionId, messageId) {
5254
- const provider = sessionProviders.get(sessionId);
5390
+ const provider = sessionProviders.get(sessionId)?.provider;
5255
5391
  if (provider?.readMessageOrdinalById) {
5256
5392
  return provider.readMessageOrdinalById(messageId);
5257
5393
  }
@@ -5288,7 +5424,7 @@ function readRawSessionMessageOrdinalById2(sessionId, messageId) {
5288
5424
  return withReadOnlySessionDb((db) => readRawSessionMessageOrdinalByIdFromDb(db, sessionId, messageId));
5289
5425
  }
5290
5426
  function compareRawSessionMessageOrder2(sessionId, leftId, rightId) {
5291
- const provider = sessionProviders.get(sessionId);
5427
+ const provider = sessionProviders.get(sessionId)?.provider;
5292
5428
  if (provider) {
5293
5429
  if (!provider.readMessageOrdinalById)
5294
5430
  return null;
@@ -5312,7 +5448,7 @@ function compareRawSessionMessageOrder2(sessionId, leftId, rightId) {
5312
5448
  });
5313
5449
  }
5314
5450
  function readRawSessionMessageById2(sessionId, messageId) {
5315
- const provider = sessionProviders.get(sessionId);
5451
+ const provider = sessionProviders.get(sessionId)?.provider;
5316
5452
  if (provider?.readMessageById) {
5317
5453
  return provider.readMessageById(messageId);
5318
5454
  }
@@ -5324,7 +5460,7 @@ function readRawSessionMessageById2(sessionId, messageId) {
5324
5460
  return withReadOnlySessionDb((db) => readRawSessionMessageByIdFromDb(db, sessionId, messageId));
5325
5461
  }
5326
5462
  function readRawSessionMessagesFromSource(sessionId) {
5327
- const provider = sessionProviders.get(sessionId);
5463
+ const provider = sessionProviders.get(sessionId)?.provider;
5328
5464
  if (provider)
5329
5465
  return provider.readMessages();
5330
5466
  if (!openCodeDbExists())
@@ -5332,7 +5468,7 @@ function readRawSessionMessagesFromSource(sessionId) {
5332
5468
  return withReadOnlySessionDb((db) => readRawSessionMessagesFromDb(db, sessionId));
5333
5469
  }
5334
5470
  function getRawSessionMessageCount2(sessionId) {
5335
- const provider = sessionProviders.get(sessionId);
5471
+ const provider = sessionProviders.get(sessionId)?.provider;
5336
5472
  if (provider) {
5337
5473
  if (provider.getMessageCount)
5338
5474
  return provider.getMessageCount();
@@ -5602,7 +5738,7 @@ function readSessionChunk2(sessionId, tokenBudget, offset = 1, eligibleEndOrdina
5602
5738
  const meta = { ordinal: msg.ordinal, messageId: msg.id };
5603
5739
  if (isHostUnservedRow(msg))
5604
5740
  markHostUnservedRow(meta);
5605
- if (msg.role === "user" && !hasMeaningfulUserText2(msg.parts)) {
5741
+ if (msg.role === "user" && !hasMeaningfulChunkUserText(msg.parts)) {
5606
5742
  const tcSummaries = msg.parts.flatMap((part) => {
5607
5743
  if (expandedResults.has(part))
5608
5744
  return [];
@@ -5740,4 +5876,4 @@ function readSessionChunk2(sessionId, tokenBudget, offset = 1, eligibleEndOrdina
5740
5876
  toolResultBoundaries
5741
5877
  };
5742
5878
  }
5743
- export { canonicalModelIdentity, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, toolTemplateError, DEFAULT_PROTECTED_TOOLS, normalizeProtectedToolName, mergeProtectedTools, detectThinkingBindingMismatch, isPrefixBoundThinkingModel, detectOverflow, stableStringify, UNKNOWN_FIT_RATIO, resolveDecisionCalibration, hasMeasuredDecisionCalibration, providerMass, localBudget, calibrationForModelKey, historyLocalBudget, CTX_REDUCE_KEEP, protectedToolTagNumbers, protectedToolTokenCount, removeSystemReminders, hasMeaningfulUserText2, extractTexts2, preloadTokenizer, hasTokenizerForFit, tokenCountUsesByteBound, estimateTokens, estimateFixedPromptTokens, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, TEXT_TAG_IDENTITY_MARKER, estimateImageTokensFromDataUrl, TODO_STATUSES, TODO_PRIORITIES, TITLE_DONE_STATUSES, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, compareMeasuredTailPrefix, formatTailHygienePrefixMismatch, freezeTailHygieneMeasurement, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, measureEmergencyTag, closeQuietly, isKnownAutocommit, installV3PerfSchema, queuePendingOp, queuePendingDropForUnchangedTag, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, updateTagByteSize, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, getReasoningTokenEstimatesByMessage, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, getInertWhitespaceAssistantTags, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, TAG_SELECT_COLUMNS, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getNewestToolTagNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getTagById, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, resolveOpenCodeDbPath, hasV1MessageTables, assertOpenCodeStoreGeneration, withReadOnlySessionDb, expandToolPart, retreatPastHostUnservedRows, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, hasUserAnswerMetadata, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, setDatabase, loadToolDefinitionMeasurements, modelAcceptsEmptyContent, isAnthropicFamilyRoute, variantChangeBustsProviderCache, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, visitRawSessionMessages2, readRawSessionMessageRange2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageIdOrdinalsForRange2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, readSessionChunk2 };
5879
+ export { canonicalModelIdentity, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, toolTemplateError, DEFAULT_PROTECTED_TOOLS, normalizeProtectedToolName, mergeProtectedTools, detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, stableStringify, UNKNOWN_FIT_RATIO, resolveDecisionCalibration, hasMeasuredDecisionCalibration, providerMass, localBudget, calibrationForModelKey, historyLocalBudget, adoptedProtectedToolsPolicy, protectedToolTagNumbers, protectedToolTokenCount, removeSystemReminders, hasMeaningfulUserText2, extractTexts2, preloadTokenizer, hasTokenizerForFit, tokenCountUsesByteBound, estimateTokens, estimateFixedPromptTokens, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, TEXT_TAG_IDENTITY_MARKER, contentTagOwnerMessageId, estimateImageTokensFromDataUrl, TODO_STATUSES, TODO_PRIORITIES, TITLE_DONE_STATUSES, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, compareMeasuredTailPrefix, formatTailHygienePrefixMismatch, freezeTailHygieneMeasurement, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, measureEmergencyTag, closeQuietly, isKnownAutocommit, installV3PerfSchema, queuePendingOp, queuePendingDropForUnchangedTag, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, updateTagByteSize, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, getReasoningTokenEstimatesByMessage, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, getInertWhitespaceAssistantTags, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, TAG_SELECT_COLUMNS, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getNewestToolTagNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getTagById, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, resolveOpenCodeDbPath, hasV1MessageTables, assertOpenCodeStoreGeneration, withReadOnlySessionDb, expandToolPart, retreatPastHostUnservedRows, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, hasUserAnswerMetadata, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, setDatabase, loadToolDefinitionMeasurements, modelAcceptsEmptyContent, isAnthropicFamilyRoute, variantChangeBustsProviderCache, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, visitRawSessionMessages2, readRawSessionMessageRange2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageIdOrdinalsForRange2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, readSessionChunk2 };