@cortexkit/opencode-magic-context 0.49.62 → 0.49.64

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.
Files changed (66) hide show
  1. package/dist/auto-search-worker.js +1 -1
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{context-45fde2p4.js → context-v1apxpct.js} +18 -23
  4. package/dist/features/magic-context/overflow-detection.d.ts +0 -20
  5. package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
  6. package/dist/features/magic-context/storage-tags.d.ts +7 -0
  7. package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
  8. package/dist/features/magic-context/transform-decision-log.d.ts +13 -0
  9. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  10. package/dist/{index-tq20edcs.js → index-0ab398z2.js} +2 -2
  11. package/dist/{index-qdver0af.js → index-5fbeycst.js} +6 -6
  12. package/dist/{index-d0feqcs5.js → index-6kgsfb81.js} +1 -1
  13. package/dist/{index-3hk445am.js → index-71h616be.js} +1 -1
  14. package/dist/{index-ev2rrjfc.js → index-7dj3s7qq.js} +1 -1
  15. package/dist/{index-zz4k3f65.js → index-aq4yfcq6.js} +47 -49
  16. package/dist/{index-3yyfftqq.js → index-c0k54yhd.js} +3 -3
  17. package/dist/{index-ywxvdwmj.js → index-ezr8mr1c.js} +1 -1
  18. package/dist/{index-s2jdky2x.js → index-g59gpt1j.js} +3 -3
  19. package/dist/{index-kv4ntrr6.js → index-gwb2wpz7.js} +2 -2
  20. package/dist/{index-s2qsd3w9.js → index-hs9xxmmy.js} +5 -5
  21. package/dist/{index-8sc7vqt7.js → index-kvfrse61.js} +75 -43
  22. package/dist/{index-3wq9btxt.js → index-m568xww6.js} +3 -3
  23. package/dist/{index-0cz8bsyx.js → index-qn27gh4e.js} +1 -1
  24. package/dist/{index-4yjn3er4.js → index-zdd01nhc.js} +5 -5
  25. package/dist/index.js +18 -18
  26. package/dist/{message-index-bounded-f6yz4xq8.js → message-index-bounded-zs7ah2te.js} +3 -3
  27. package/dist/migration-worker.js +1 -1
  28. package/dist/raw-ordinal-warmup-worker.js +4 -4
  29. package/dist/{read-session-chunk-8b1g06nz.js → read-session-chunk-jf2f8jz8.js} +2 -2
  30. package/dist/{recomp-orchestrator-7s8nyzhy.js → recomp-orchestrator-6vxnrh2w.js} +7 -7
  31. package/dist/{render-nrfbtkkw.js → render-n46wpv2n.js} +6 -6
  32. package/dist/{search-archive-1ppdjfm9.js → search-archive-9k6vsp44.js} +4 -4
  33. package/dist/{search-xha0r30f.js → search-s386bwwh.js} +5 -5
  34. package/dist/shared/tag-transcript.d.ts.map +1 -1
  35. package/dist/{storage-tags-spet01yb.js → storage-tags-2r952wqy.js} +1 -1
  36. package/dist/{transform-postprocess-phase-fxp1atm1.js → transform-postprocess-phase-jjc9jcer.js} +8 -8
  37. package/dist/v2/auto-search-worker.js +1 -1
  38. package/dist/v2/chunk-embedding-write-worker.js +1 -1
  39. package/dist/v2/{context-77g3jhf2.js → context-nfkhb5sv.js} +41 -40
  40. package/dist/v2/hooks/context.d.ts.map +1 -1
  41. package/dist/v2/{message-index-bounded-0w8eh8fc.js → message-index-bounded-axbs1s97.js} +3 -3
  42. package/dist/v2/migration-worker.js +1 -1
  43. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  44. package/dist/v2/{read-session-chunk-dxs1tgt9.js → read-session-chunk-41cm522x.js} +2 -2
  45. package/dist/v2/{recomp-orchestrator-zc1wdv9q.js → recomp-orchestrator-krccyz0a.js} +6 -6
  46. package/dist/v2/{render-9knrdrjs.js → render-7v7yx9xb.js} +6 -6
  47. package/dist/v2/{search-archive-2jmyvj69.js → search-archive-1yc8bh6y.js} +4 -4
  48. package/dist/v2/{search-a2a0qs3t.js → search-mabwkzw2.js} +4 -4
  49. package/dist/v2/{server-svx20ra2.js → server-8w9b5exq.js} +1 -1
  50. package/dist/v2/{server-9m5r04ws.js → server-anh8gf0w.js} +2 -2
  51. package/dist/v2/{server-ja6swvmb.js → server-bh9yzxpz.js} +2 -2
  52. package/dist/v2/{server-9ab9jnpq.js → server-bnka2vf2.js} +3 -3
  53. package/dist/v2/{server-8ycacd59.js → server-cdddk5d1.js} +1 -1
  54. package/dist/v2/{server-88n85n60.js → server-hb5zm7yh.js} +75 -43
  55. package/dist/v2/{server-tzh55x6d.js → server-hcgqsdrh.js} +1 -1
  56. package/dist/v2/{server-4r86tcs2.js → server-k97r77x3.js} +2 -2
  57. package/dist/v2/{server-8hcxmt1w.js → server-xse5jngy.js} +5 -5
  58. package/dist/v2/{server-t8tmrtcg.js → server-yxw43z2w.js} +1 -1
  59. package/dist/v2/server.js +2 -2
  60. package/dist/v2/{storage-tags-50wsqg3t.js → storage-tags-9zs0gc7w.js} +1 -1
  61. package/dist/v2/{v2-archive-reader-ycjh6a2d.js → v2-archive-reader-pgk140pb.js} +1 -1
  62. package/dist/v2/{wrapup-orchestrator-fyyb28jf.js → wrapup-orchestrator-v2rgtczc.js} +6 -6
  63. package/dist/{v2-archive-reader-wec0a8fx.js → v2-archive-reader-cv6veqnz.js} +1 -1
  64. package/dist/{wrapup-orchestrator-560v99mk.js → wrapup-orchestrator-qbtg1dhm.js} +8 -8
  65. package/package.json +1 -1
  66. package/src/shared/tag-transcript.ts +105 -1
@@ -4981,6 +4981,11 @@ function markDropLeavesReasoning(db, sessionId) {
4981
4981
  }
4982
4982
 
4983
4983
  // src/features/magic-context/overflow-detection.ts
4984
+ var TOKEN_COUNT = String.raw`(?<![\d+_-])(?:\d+(?:[,_ .\u202f]+\d+)*(?=\s*tokens?\b)|\d+(?:[,_ \u202f]+\d+)*)(?!\w|[,_\s.]+\d)`;
4985
+ var ESTIMATED_REQUEST = String.raw`\bthis request has an estimated\b`;
4986
+ function overflowPattern(strings, ...fragments) {
4987
+ return new RegExp(String.raw(strings, ...fragments), "i");
4988
+ }
4984
4989
  var OVERFLOW_PATTERNS = [
4985
4990
  /prompt is too long/i,
4986
4991
  /input is too long for requested model/i,
@@ -4988,7 +4993,7 @@ var OVERFLOW_PATTERNS = [
4988
4993
  /input token count.*exceeds the maximum/i,
4989
4994
  /maximum prompt length is \d+/i,
4990
4995
  /reduce the length of the messages/i,
4991
- /maximum context length is \d+ tokens/i,
4996
+ overflowPattern`maximum context length is ${TOKEN_COUNT} tokens?\b`,
4992
4997
  /maximum model length is \d+/i,
4993
4998
  /exceeds the limit of \d+/i,
4994
4999
  /exceeds the available context size/i,
@@ -4997,48 +5002,84 @@ var OVERFLOW_PATTERNS = [
4997
5002
  /exceeded model token limit/i,
4998
5003
  /context[_ ]length[_ ]exceeded/i,
4999
5004
  /request entity too large/i,
5000
- /context length is only \d+ tokens/i,
5005
+ overflowPattern`context length is only ${TOKEN_COUNT} tokens?\b`,
5001
5006
  /input length.*exceeds.*context length/i,
5002
5007
  /\bContextWindowExceededError\b/i,
5003
- /\bthe input \(\d+ tokens?\) is longer than the model's context length \(\d+ tokens?\)/i,
5008
+ overflowPattern`\bthe input \(${TOKEN_COUNT} tokens?\) is longer than the model's context length \(${TOKEN_COUNT} tokens?\)`,
5004
5009
  /prompt too long; exceeded (?:max )?context length/i,
5005
- /too large for model with \d+ maximum context length/i,
5010
+ overflowPattern`too large for model with ${TOKEN_COUNT} maximum context length`,
5006
5011
  /model_context_window_exceeded/i,
5007
5012
  /context size has been exceeded/i,
5008
5013
  /prepared prompt exceeds engine max_context/i,
5009
5014
  /prompt exceeds (?:the )?.{0,32}\bmax_context\b/i
5010
5015
  ];
5011
5016
  var LIMIT_EXTRACTION_PATTERNS = [
5012
- { pattern: /maximum prompt length is (\d+)/i, provenance: "prompt_only" },
5013
5017
  {
5014
- pattern: /maximum context length is (\d+) tokens?/i,
5018
+ pattern: overflowPattern`maximum prompt length is (${TOKEN_COUNT})`,
5019
+ provenance: "prompt_only"
5020
+ },
5021
+ {
5022
+ pattern: overflowPattern`maximum context length is (${TOKEN_COUNT}) tokens?\b`,
5015
5023
  provenance: "combined"
5016
5024
  },
5017
- { pattern: /maximum model length is (\d+)/i, provenance: "combined" },
5018
- { pattern: /context length is only (\d+) tokens?/i, provenance: "combined" },
5019
- { pattern: /exceeds the limit of (\d+)/i, provenance: "unknown" },
5025
+ { pattern: overflowPattern`maximum model length is (${TOKEN_COUNT})`, provenance: "combined" },
5020
5026
  {
5021
- pattern: /too large for model with (\d+) maximum context length/i,
5027
+ pattern: overflowPattern`context length is only (${TOKEN_COUNT}) tokens?\b`,
5022
5028
  provenance: "combined"
5023
5029
  },
5024
- { pattern: /context size[^0-9]{0,40}(\d{4,})\s*tokens?/i, provenance: "combined" },
5025
- { pattern: /exceeds? the context length of (\d+)/i, provenance: "combined" },
5030
+ { pattern: overflowPattern`exceeds the limit of (${TOKEN_COUNT})`, provenance: "unknown" },
5026
5031
  {
5027
- pattern: /\bthe input \(\d+ tokens?\) is longer than the model's context length \((\d+) tokens?\)/i,
5032
+ pattern: overflowPattern`too large for model with (${TOKEN_COUNT}) maximum context length`,
5028
5033
  provenance: "combined"
5029
5034
  },
5030
5035
  {
5031
- pattern: />\s*(\d+)\s*(?:tokens?\s*)?(?:maximum|max|limit)\b/i,
5036
+ pattern: overflowPattern`context size[^0-9]{0,40}(${TOKEN_COUNT})\s*tokens?\b`,
5037
+ provenance: "combined"
5038
+ },
5039
+ {
5040
+ pattern: overflowPattern`exceeds? the context length of (${TOKEN_COUNT})`,
5041
+ provenance: "combined"
5042
+ },
5043
+ {
5044
+ pattern: overflowPattern`\bthe input \(${TOKEN_COUNT} tokens?\) is longer than the model's context length \((${TOKEN_COUNT}) tokens?\)`,
5045
+ provenance: "combined"
5046
+ },
5047
+ {
5048
+ pattern: overflowPattern`>\s*(${TOKEN_COUNT})\s*(?:tokens?\s*)?(?:maximum|max|limit)\b`,
5032
5049
  provenance: "prompt_only"
5033
5050
  },
5034
5051
  {
5035
- pattern: /maximum number of tokens allowed\s*\(?\s*(\d+)/i,
5052
+ pattern: overflowPattern`maximum number of tokens allowed\s*\(?\s*(${TOKEN_COUNT})`,
5036
5053
  provenance: "prompt_only"
5037
5054
  },
5038
- { pattern: /prepared prompt exceeds engine max_context\s+(\d+)/i, provenance: "unknown" },
5039
- { pattern: /prompt exceeds (?:the )?.{0,32}\bmax_context\s+(\d+)/i, provenance: "unknown" },
5040
- { pattern: /max(?:imum)?.*context.*?(\d+)/i, provenance: "unknown" }
5055
+ {
5056
+ pattern: overflowPattern`prepared prompt exceeds engine max_context\s+(${TOKEN_COUNT})`,
5057
+ provenance: "unknown"
5058
+ },
5059
+ {
5060
+ pattern: overflowPattern`prompt exceeds (?:the )?.{0,32}\bmax_context\s+(${TOKEN_COUNT})`,
5061
+ provenance: "unknown"
5062
+ },
5063
+ {
5064
+ pattern: overflowPattern`\ballows a context of up to (${TOKEN_COUNT}) tokens?\b`,
5065
+ provenance: "combined"
5066
+ },
5067
+ {
5068
+ pattern: overflowPattern`(?<!${ESTIMATED_REQUEST}\s+)\bup to (${TOKEN_COUNT}) tokens?\b`,
5069
+ provenance: "unknown"
5070
+ },
5071
+ {
5072
+ pattern: overflowPattern`max(?:imum)?.*context(?:(?!${ESTIMATED_REQUEST})[^\d\r\n])*(${TOKEN_COUNT})`,
5073
+ provenance: "unknown"
5074
+ }
5041
5075
  ];
5076
+ function parseTokenCount(raw) {
5077
+ if (raw === undefined || !/^(?:\d+|\d{1,3}([,_ .\u202f])\d{3}(?:\1\d{3})*)$/.test(raw)) {
5078
+ return null;
5079
+ }
5080
+ const value = Number(raw.replace(/[,_ .\u202f]/g, ""));
5081
+ return Number.isSafeInteger(value) ? value : null;
5082
+ }
5042
5083
  var MIN_PLAUSIBLE_LIMIT = 1024;
5043
5084
  var MAX_PLAUSIBLE_LIMIT = 1e7;
5044
5085
  var THINKING_BINDING_MISMATCH_PATTERN = /bound to a different conversation/i;
@@ -5160,24 +5201,22 @@ function detectOverflow(error) {
5160
5201
  matchedPattern: matched?.source
5161
5202
  };
5162
5203
  }
5204
+ var INPUT_EXTRACTION_PATTERNS = [
5205
+ overflowPattern`prompt is too long:\s*(${TOKEN_COUNT})`,
5206
+ overflowPattern`input token count\s*\(?\s*(${TOKEN_COUNT})`,
5207
+ overflowPattern`input length\s*(${TOKEN_COUNT})`,
5208
+ overflowPattern`prompt was\s*(${TOKEN_COUNT})`,
5209
+ overflowPattern`messages resulted in\s*(${TOKEN_COUNT})\s*tokens?\b`,
5210
+ overflowPattern`\bthe input \((${TOKEN_COUNT}) tokens?\) is longer than the model's context length \(${TOKEN_COUNT} tokens?\)`,
5211
+ overflowPattern`\(\s*(${TOKEN_COUNT})\s+in the messages,\s*${TOKEN_COUNT}\s+in the completion\s*\)`,
5212
+ overflowPattern`${ESTIMATED_REQUEST}\s+(${TOKEN_COUNT})`
5213
+ ];
5163
5214
  function parseReportedInputTokens(message) {
5164
5215
  if (!message)
5165
5216
  return;
5166
- const patterns = [
5167
- /prompt is too long:\s*(\d+)/i,
5168
- /input token count\s*\(?\s*(\d+)/i,
5169
- /input length\s*(\d+)/i,
5170
- /prompt was\s*(\d+)/i,
5171
- /messages resulted in\s*(\d+)\s*tokens?/i,
5172
- /\bthe input \((\d+) tokens?\) is longer than the model's context length \(\d+ tokens?\)/i,
5173
- /\(\s*(\d+)\s+in the messages,\s*\d+\s+in the completion\s*\)/i
5174
- ];
5175
- for (const pattern of patterns) {
5176
- const raw = message.match(pattern)?.[1];
5177
- if (!raw)
5178
- continue;
5179
- const value = Number.parseInt(raw, 10);
5180
- if (Number.isFinite(value) && value > 0)
5217
+ for (const pattern of INPUT_EXTRACTION_PATTERNS) {
5218
+ const value = parseTokenCount(message.match(pattern)?.[1]);
5219
+ if (value !== null && value > 0)
5181
5220
  return value;
5182
5221
  }
5183
5222
  return;
@@ -5186,16 +5225,8 @@ function parseReportedLimit(message) {
5186
5225
  if (!message)
5187
5226
  return;
5188
5227
  for (const { pattern, provenance } of LIMIT_EXTRACTION_PATTERNS) {
5189
- const match = message.match(pattern);
5190
- if (!match)
5191
- continue;
5192
- const raw = match[1];
5193
- if (!raw)
5194
- continue;
5195
- const value = Number.parseInt(raw, 10);
5196
- if (!Number.isFinite(value))
5197
- continue;
5198
- if (value < MIN_PLAUSIBLE_LIMIT || value > MAX_PLAUSIBLE_LIMIT)
5228
+ const value = parseTokenCount(message.match(pattern)?.[1]);
5229
+ if (value === null || value < MIN_PLAUSIBLE_LIMIT || value > MAX_PLAUSIBLE_LIMIT)
5199
5230
  continue;
5200
5231
  return { value, provenance };
5201
5232
  }
@@ -7380,6 +7411,7 @@ function getActiveTagTokenTotalsByMessage2(db, sessionId, messageIds) {
7380
7411
  return out;
7381
7412
  }
7382
7413
  var updateTagTokenCountStatements = new WeakMap;
7414
+ var setTagTokenCountStatements = new WeakMap;
7383
7415
  var updateTagInputTokenCountStatements = new WeakMap;
7384
7416
  function getUpdateTagTokenCountStatement(db) {
7385
7417
  let stmt = updateTagTokenCountStatements.get(db);
@@ -1021,7 +1021,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
1021
1021
  state.running = startMessageFtsRowidMapBackfill2(db, signal).then(async () => {
1022
1022
  if (signal.aborted || !readsOpenCodeStore)
1023
1023
  return;
1024
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-dxs1tgt9.js"));
1024
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-41cm522x.js"));
1025
1025
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-ynb3vg6r.js"));
1026
1026
  if (signal.aborted)
1027
1027
  return;
@@ -3,12 +3,12 @@ import {
3
3
  } from "./server-y8xjr8rx.js";
4
4
  import {
5
5
  getTagById2
6
- } from "./server-88n85n60.js";
6
+ } from "./server-hb5zm7yh.js";
7
7
  import {
8
8
  expandToolPart,
9
9
  visitRawSessionMessages2,
10
10
  readRawSessionMessageById2
11
- } from "./server-8ycacd59.js";
11
+ } from "./server-cdddk5d1.js";
12
12
 
13
13
  // src/tools/ctx-expand/render.ts
14
14
  import { createHash } from "node:crypto";
@@ -100,7 +100,7 @@ import {
100
100
  foldShrunkPartTags2,
101
101
  getTagNumberByMessageId2,
102
102
  getActiveTagsBySession2
103
- } from "./server-88n85n60.js";
103
+ } from "./server-hb5zm7yh.js";
104
104
  import {
105
105
  hasMeaningfulUserText2,
106
106
  estimateTokens,
@@ -155,14 +155,14 @@ import {
155
155
  getRawSessionTagKeysThrough2,
156
156
  getLegacyProtectedTailStartOrdinal2,
157
157
  readSessionChunk2
158
- } from "./server-8ycacd59.js";
158
+ } from "./server-cdddk5d1.js";
159
159
  import {
160
160
  clearCompressionDepth,
161
161
  clearCompressionDepthRange,
162
162
  toMessageIndexSource,
163
163
  clearIndexedMessagesInTransaction,
164
164
  indexSourcesAfterOrdinal
165
- } from "./server-svx20ra2.js";
165
+ } from "./server-8w9b5exq.js";
166
166
  import {
167
167
  COMPARTMENT_LEASE_RENEWAL_MS,
168
168
  getCompartmentLeaseBlocker,
@@ -207,7 +207,7 @@ import {
207
207
  getProjectState,
208
208
  recordSubagentInvocation,
209
209
  getLatestHistorianInvocationId
210
- } from "./server-t8tmrtcg.js";
210
+ } from "./server-yxw43z2w.js";
211
211
  import {
212
212
  invalidateAutoEmbedSession
213
213
  } from "./server-2amn2s73.js";
@@ -267,7 +267,7 @@ import {
267
267
  LATEST_SUPPORTED_VERSION,
268
268
  getPersistedSchemaVersion,
269
269
  openDatabase
270
- } from "./server-tzh55x6d.js";
270
+ } from "./server-hcgqsdrh.js";
271
271
  import {
272
272
  parseCompartmentOutput,
273
273
  resolveWorkspaceShareCategories,
@@ -57,7 +57,7 @@ import {
57
57
  getPendingPiCompactionMarkerState,
58
58
  logPiCompactionMarkerClear,
59
59
  isPrefixBoundThinkingModel
60
- } from "./server-88n85n60.js";
60
+ } from "./server-hb5zm7yh.js";
61
61
  import {
62
62
  BoundedSessionMap,
63
63
  getMeasuredToolDefinitionTokens,
package/dist/v2/server.js CHANGED
@@ -7875,7 +7875,7 @@ var require_src2 = __commonJS(function(exports, module) {
7875
7875
  // package.json
7876
7876
  var package_default = {
7877
7877
  name: "@cortexkit/opencode-magic-context",
7878
- version: "0.49.62",
7878
+ version: "0.49.64",
7879
7879
  type: "module",
7880
7880
  description: "OpenCode plugin for Magic Context — cross-session memory and context management",
7881
7881
  main: "dist/index.js",
@@ -8196,7 +8196,7 @@ async function setup(context) {
8196
8196
  if (claimStorageBackupWarningCheck() && isMagicContextStorageOutsideEngram(storageDir)) {
8197
8197
  log2(`[magic-context] Magic Context storage is at ${storageDir}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.`);
8198
8198
  }
8199
- const { registerContext } = await import("./context-77g3jhf2.js");
8199
+ const { registerContext } = await import("./context-nfkhb5sv.js");
8200
8200
  setHarness2("opencode2");
8201
8201
  bindStaleBuildNotice({}, import.meta.url, "opencode2");
8202
8202
  const duties = await registerContext(context);
@@ -64,7 +64,7 @@ import {
64
64
  adoptNullOwnerToolTag2,
65
65
  getCandidateToolOwners2,
66
66
  pickNearestPriorOwner2
67
- } from "./server-88n85n60.js";
67
+ } from "./server-hb5zm7yh.js";
68
68
  import"./server-1zx87sdm.js";
69
69
  import"./server-rz6g5xne.js";
70
70
  import"./server-xepx8t43.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readV2ArchiveOffThread2,
3
3
  serveV2ArchiveReads2
4
- } from "./server-9ab9jnpq.js";
4
+ } from "./server-bnka2vf2.js";
5
5
  import"./server-v0p37hm2.js";
6
6
  import"./server-gzy5w8ya.js";
7
7
  import"./server-1d042x6w.js";
@@ -11,7 +11,7 @@ import {
11
11
  releaseCompartmentLeaseBestEffort,
12
12
  getCompartments,
13
13
  getLastCompartmentEndMessage
14
- } from "./server-t8tmrtcg.js";
14
+ } from "./server-yxw43z2w.js";
15
15
  import"./server-2amn2s73.js";
16
16
  import"./server-y8xjr8rx.js";
17
17
  import"./server-x6fn9x8q.js";
@@ -24,7 +24,7 @@ import"./server-1d042x6w.js";
24
24
  import"./server-6ash6z8z.js";
25
25
  import"./server-ds8vpfkr.js";
26
26
  import"./server-8pdfmc27.js";
27
- import"./server-svx20ra2.js";
27
+ import"./server-8w9b5exq.js";
28
28
  import {
29
29
  getWrapupInProgressState,
30
30
  acquireWrapupInProgress,
@@ -32,16 +32,16 @@ import {
32
32
  releaseWrapupInProgress,
33
33
  getHistorianFailureState,
34
34
  clearEmergencyRecovery
35
- } from "./server-88n85n60.js";
35
+ } from "./server-hb5zm7yh.js";
36
36
  import"./server-xepx8t43.js";
37
- import"./server-tzh55x6d.js";
37
+ import"./server-hcgqsdrh.js";
38
38
  import"./server-1zx87sdm.js";
39
39
  import"./server-rz6g5xne.js";
40
40
  import"./server-2ra6pwf3.js";
41
41
  import"./server-3ap5dmhc.js";
42
42
  import {
43
43
  prepareRawSessionOrdinals2
44
- } from "./server-8ycacd59.js";
44
+ } from "./server-cdddk5d1.js";
45
45
  import"./server-fr0wbhdn.js";
46
46
  import"./server-jn4pktdk.js";
47
47
  import"./server-afsz3cmx.js";
@@ -63,7 +63,7 @@ import {
63
63
  registerActiveCompartmentRun,
64
64
  setRecompStarting2,
65
65
  setRecompTerminal2
66
- } from "./server-8hcxmt1w.js";
66
+ } from "./server-xse5jngy.js";
67
67
  import"./server-qt1qqasc.js";
68
68
  import"./server-z5255w05.js";
69
69
  import"./server-jtq03rkb.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readV2ArchiveOffThread2,
3
3
  serveV2ArchiveReads2
4
- } from "./index-s2jdky2x.js";
4
+ } from "./index-g59gpt1j.js";
5
5
  import"./index-v0p37hm2.js";
6
6
  import"./index-gzy5w8ya.js";
7
7
  import"./index-1d042x6w.js";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  runManagedWrapup2
3
- } from "./index-s2qsd3w9.js";
4
- import"./index-3wq9btxt.js";
5
- import"./index-4yjn3er4.js";
3
+ } from "./index-hs9xxmmy.js";
4
+ import"./index-m568xww6.js";
5
+ import"./index-zdd01nhc.js";
6
6
  import"./index-832w615x.js";
7
7
  import"./index-sd3egckz.js";
8
8
  import"./index-n6aye6ny.js";
@@ -10,16 +10,16 @@ import"./index-zxj39ba2.js";
10
10
  import"./index-jjvbk92s.js";
11
11
  import"./index-gq1g9a3a.js";
12
12
  import"./index-4dhv7mqz.js";
13
- import"./index-ywxvdwmj.js";
13
+ import"./index-ezr8mr1c.js";
14
14
  import"./index-tebcx987.js";
15
- import"./index-ev2rrjfc.js";
15
+ import"./index-7dj3s7qq.js";
16
16
  import"./index-2amn2s73.js";
17
17
  import"./index-6athgjba.js";
18
18
  import"./index-ngwmx6nt.js";
19
19
  import"./index-1sq1krqw.js";
20
20
  import"./index-qt1qqasc.js";
21
- import"./index-d0feqcs5.js";
22
- import"./index-8sc7vqt7.js";
21
+ import"./index-6kgsfb81.js";
22
+ import"./index-kvfrse61.js";
23
23
  import"./index-1zx87sdm.js";
24
24
  import"./index-x40zr813.js";
25
25
  import"./index-x8a7jmkh.js";
@@ -29,7 +29,7 @@ import"./index-6nqz8hsz.js";
29
29
  import"./index-jg7sbt3v.js";
30
30
  import"./index-snbpdpa3.js";
31
31
  import"./index-pxnzyvjc.js";
32
- import"./index-0cz8bsyx.js";
32
+ import"./index-qn27gh4e.js";
33
33
  import"./index-fb3zxn06.js";
34
34
  import"./index-xx05vta0.js";
35
35
  import"./index-fr0wbhdn.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-magic-context",
3
- "version": "0.49.62",
3
+ "version": "0.49.64",
4
4
  "type": "module",
5
5
  "description": "OpenCode plugin for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",
@@ -49,6 +49,7 @@ import { createHash } from "node:crypto";
49
49
  import type { ContextDatabase } from "../features/magic-context/storage";
50
50
  import { saveSourceContent } from "../features/magic-context/storage-source";
51
51
  import {
52
+ setTagTokenCount,
52
53
  updateTagByteSize,
53
54
  updateTagInputByteSize,
54
55
  updateTagInputTokenCount,
@@ -296,6 +297,12 @@ interface ToolOccurrence {
296
297
  originalInput?: Record<string, unknown>;
297
298
  }
298
299
 
300
+ interface ResultTextBlock {
301
+ part: TranscriptPart;
302
+ text: string;
303
+ tokenCacheKey: string;
304
+ }
305
+
299
306
  interface TagTranscriptTiming {
300
307
  identity: number;
301
308
  prefix: number;
@@ -310,8 +317,18 @@ interface ToolAggregate {
310
317
  occurrences: ToolOccurrence[];
311
318
  /** Largest byteSize seen across occurrences — used as the tag size. */
312
319
  maxByteSize: number;
313
- /** Token count paired with maxByteSize (the same output occurrence). */
320
+ /**
321
+ * Token count paired with maxByteSize (the same output occurrence). A result
322
+ * that carries images instead counts its largest text block plus every image
323
+ * at the host's per-image cost (see applyImageResultAccounting).
324
+ */
314
325
  maxTokenCount: number;
326
+ /** Per-image token cost of the image blocks in this pass's result occurrences. */
327
+ resultImageTokens: number;
328
+ /** This pass's result text blocks, before the tag prefix, for applyImageResultAccounting. */
329
+ resultTexts: ResultTextBlock[];
330
+ /** Set when applyGrownToolResultAccounting wrote this pass (its write keeps the larger count). */
331
+ tokenCountGrewThisPass?: boolean;
315
332
  /** Tool name from the first occurrence we see one on. */
316
333
  toolName: string | null;
317
334
  /** Input byte size from the invocation occurrence (for storage projection). */
@@ -572,6 +589,9 @@ export function tagTranscript(
572
589
  if (timing) timing.identity += performance.now() - identityStart;
573
590
  }
574
591
  existing.identityReusable &&= reuseIdentity;
592
+ if (part.kind === "tool_result") {
593
+ noteResultBlock(existing, part, text, tokenCacheKey);
594
+ }
575
595
  applyToolPrefixAndTarget({
576
596
  skipPrefixInjection,
577
597
  part,
@@ -612,6 +632,8 @@ export function tagTranscript(
612
632
  // genuinely larger folded result can still bump accounting.
613
633
  maxByteSize: reusableAccounting.byteSize,
614
634
  maxTokenCount: reusableAccounting.tokenCount ?? 0,
635
+ resultImageTokens: 0,
636
+ resultTexts: [],
615
637
  toolName: null,
616
638
  inputByteSize: reusableAccounting.inputByteSize,
617
639
  inputTokenCount: reusableAccounting.inputTokenCount,
@@ -674,6 +696,8 @@ export function tagTranscript(
674
696
  occurrences: [{ message, part, kind: part.kind }],
675
697
  maxByteSize: persistedAccounting?.byteSize ?? outputByteSize,
676
698
  maxTokenCount: persistedAccounting?.tokenCount ?? outputTokenCount,
699
+ resultImageTokens: 0,
700
+ resultTexts: [],
677
701
  toolName: accounting.toolName,
678
702
  inputByteSize:
679
703
  persistedAccounting?.inputByteSize ??
@@ -703,6 +727,8 @@ export function tagTranscript(
703
727
  toolAggregates.set(aggregateKey, aggregate);
704
728
  if (part.kind === "tool_use") {
705
729
  openToolAggregateKeysByCallId.set(callId, [...pendingKeys, aggregateKey]);
730
+ } else {
731
+ noteResultBlock(aggregate, part, text, tokenCacheKey);
706
732
  }
707
733
  applyToolPrefixAndTarget({
708
734
  skipPrefixInjection,
@@ -723,6 +749,17 @@ export function tagTranscript(
723
749
  }
724
750
  }
725
751
 
752
+ for (const aggregate of toolAggregates.values()) {
753
+ applyImageResultAccounting({
754
+ db,
755
+ sessionId,
756
+ tagger,
757
+ aggregate,
758
+ timing,
759
+ tokenCache: options.toolTokenCache,
760
+ });
761
+ }
762
+
726
763
  if (timing && options.onTiming) {
727
764
  options.onTiming("identity", timing.identity);
728
765
  options.onTiming("prefix", timing.prefix);
@@ -787,11 +824,74 @@ function applyGrownToolResultAccounting(args: GrownToolResultAccountingArgs): vo
787
824
  }
788
825
  args.aggregate.maxByteSize = args.byteSize;
789
826
  args.aggregate.maxTokenCount = tokenCount;
827
+ args.aggregate.tokenCountGrewThisPass = true;
790
828
  updateTagByteSize(args.db, args.sessionId, args.aggregate.tagId, args.byteSize);
791
829
  updateTagTokenCount(args.db, args.sessionId, args.aggregate.tagId, tokenCount);
792
830
  syncToolAggregateAccounting(args.tagger, args.sessionId, args.aggregate);
793
831
  }
794
832
 
833
+ /** Record one result block of this pass; `text` must be read before the tag prefix is added. */
834
+ function noteResultBlock(
835
+ aggregate: ToolAggregate,
836
+ part: TranscriptPart,
837
+ text: string,
838
+ tokenCacheKey: string,
839
+ ): void {
840
+ const imageTokens = part.imageTokens?.() ?? 0;
841
+ if (imageTokens > 0) aggregate.resultImageTokens += imageTokens;
842
+ else if (text.length > 0) aggregate.resultTexts.push({ part, text, tokenCacheKey });
843
+ }
844
+
845
+ /**
846
+ * A tool result that carries images (Pi's `read` of a picture, an image
847
+ * generator) is sized as its largest text block plus each image at what the
848
+ * request carries for it: the host's per-image token cost while the image is
849
+ * sent, or the cost of the text placeholder sent in its place (the
850
+ * processed-image strip's marker, or the host's note for a model without image
851
+ * input; see the Pi transcript's `imageTokens`). Byte-growth accounting alone
852
+ * would leave it at the count of its largest block, an image whose bytes are
853
+ * base64, so the protected tail, the drop planners and status would see a few
854
+ * dozen tokens for an output the provider bills as an image. Runs once per
855
+ * pass after the walk, so block order does not matter. The stored count follows
856
+ * the request both ways: it rises when a row stored before images were counted
857
+ * is seen again, and falls once an image leaves the request, so a queued drop
858
+ * of an already-stripped result is not valued at the images it no longer
859
+ * removes. Replaying the same request writes nothing. Results without images
860
+ * are left untouched.
861
+ */
862
+ function applyImageResultAccounting(args: {
863
+ db: ContextDatabase;
864
+ sessionId: string;
865
+ tagger: Tagger;
866
+ aggregate: ToolAggregate & { tagId: number };
867
+ timing: TagTranscriptTiming | undefined;
868
+ tokenCache?: Map<string, { text: string; tokenCount: number }>;
869
+ }): void {
870
+ const { aggregate } = args;
871
+ if (aggregate.resultImageTokens === 0) return;
872
+ const tokenStart = args.timing ? performance.now() : 0;
873
+ let textTokens = 0;
874
+ for (const block of aggregate.resultTexts) {
875
+ textTokens = Math.max(
876
+ textTokens,
877
+ getCachedToolPartTokenCount(
878
+ block.part,
879
+ block.text,
880
+ args.tokenCache,
881
+ block.tokenCacheKey,
882
+ ),
883
+ );
884
+ }
885
+ if (args.timing) args.timing.tokenCounting += performance.now() - tokenStart;
886
+ const tokenCount = textTokens + aggregate.resultImageTokens;
887
+ // A growth write this pass keeps the larger of the stored and new counts, so
888
+ // the in-memory count may not be what the row holds; write the exact count.
889
+ if (tokenCount === aggregate.maxTokenCount && !aggregate.tokenCountGrewThisPass) return;
890
+ aggregate.maxTokenCount = tokenCount;
891
+ setTagTokenCount(args.db, args.sessionId, aggregate.tagId, tokenCount);
892
+ syncToolAggregateAccounting(args.tagger, args.sessionId, aggregate);
893
+ }
894
+
795
895
  function readAggregateToolAccounting(
796
896
  part: TranscriptPart,
797
897
  timing: TagTranscriptTiming | undefined,
@@ -960,9 +1060,13 @@ function getToolPartByteSize(part: TranscriptPart, text: string): number {
960
1060
  * Real-tokenizer mirror of {@link getToolPartByteSize}: token count of a tool
961
1061
  * part's output text (falling back to the raw payload for non-text results,
962
1062
  * matching the byte path so token_count stays consistent with byte_size).
1063
+ * An image block is the exception: it counts at the host's per-image cost, since
1064
+ * the provider bills the image, not the length of its base64 encoding.
963
1065
  */
964
1066
  function getToolPartTokenCount(part: TranscriptPart, text: string): number {
965
1067
  if (text.length > 0 || part.kind !== "tool_result") return estimateTokens(text);
1068
+ const imageTokens = part.imageTokens?.() ?? 0;
1069
+ if (imageTokens > 0) return imageTokens;
966
1070
  const raw = part.rawByteSize?.();
967
1071
  if (typeof raw === "number" && raw > 0) {
968
1072
  const record = isRecord(part) ? part : undefined;