@cortexkit/pi-magic-context 0.49.30 → 0.49.32

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 (30) hide show
  1. package/dist/auto-search-worker.js +4 -4
  2. package/dist/chunk-embedding-write-worker.js +4 -4
  3. package/dist/{compartment-chunk-embedding-pkk5beqp.js → compartment-chunk-embedding-8c85ebce.js} +1 -1
  4. package/dist/{embedding-backfill-v83xh6e8.js → embedding-backfill-rwfmyvze.js} +3 -3
  5. package/dist/{index-kmk3xpf9.js → index-0gymvr5j.js} +47 -7
  6. package/dist/{index-n2ayqhbx.js → index-87xkw8xm.js} +7 -5
  7. package/dist/{index-4nny4r40.js → index-9xd7qveg.js} +1 -1
  8. package/dist/{index-g026ztby.js → index-c474g0gj.js} +4 -18
  9. package/dist/{index-gxjppvsh.js → index-d0n9yjnc.js} +35 -13
  10. package/dist/{index-5qh6z3sn.js → index-d5q1q700.js} +1 -1
  11. package/dist/{index-2pnhk4gc.js → index-drmr22ac.js} +115 -39
  12. package/dist/{index-0cq3g9y5.js → index-e59j3yq5.js} +414 -11
  13. package/dist/{index-0x1c054v.js → index-eqw9t2ty.js} +1 -1
  14. package/dist/index-nrzkqte4.js +18 -0
  15. package/dist/{index-0s14xaca.js → index-pb3ea2tq.js} +1 -1
  16. package/dist/{index-y5x5wt5t.js → index-r9y6tbbm.js} +6 -4
  17. package/dist/{index-74bc8ts8.js → index-wpazxe9x.js} +64 -3
  18. package/dist/{index-0jykn0dw.js → index-xn5yh0pn.js} +65 -2
  19. package/dist/index.js +722 -447
  20. package/dist/{message-index-bounded-vkqx693v.js → message-index-bounded-n30vk21s.js} +4 -4
  21. package/dist/migration-worker.js +6 -5
  22. package/dist/{project-embedding-registry-wwbhm9rf.js → project-embedding-registry-acqb6be4.js} +2 -2
  23. package/dist/raw-ordinal-warmup-worker.js +3 -3
  24. package/dist/{read-session-chunk-73kd0ans.js → read-session-chunk-ka6dhc77.js} +3 -3
  25. package/dist/{search-archive-ck531w6h.js → search-archive-msy2bczx.js} +4 -4
  26. package/dist/{search-tgv2rdac.js → search-qbxrnnjb.js} +9 -9
  27. package/dist/{storage-tags-9qaasrky.js → storage-tags-6409qq18.js} +2 -2
  28. package/dist/subagent-entry.js +12 -12
  29. package/dist/tag-snapshot-worker-pi.js +11 -8
  30. package/package.json +3 -1
@@ -3,11 +3,11 @@ import {
3
3
  tagRevisionCountSql,
4
4
  tagRevisionKey,
5
5
  TAG_INSERT_CONFLICT_ROWS
6
- } from "./index-g026ztby.js";
6
+ } from "./index-c474g0gj.js";
7
7
  import {
8
8
  getTagsBySession2,
9
9
  getTagsByNumbers2
10
- } from "./index-0x1c054v.js";
10
+ } from "./index-eqw9t2ty.js";
11
11
  import {
12
12
  inRootAsyncContext2,
13
13
  getSqliteDatabasePath2,
@@ -15,7 +15,7 @@ import {
15
15
  } from "./index-2qtx0q6h.js";
16
16
  import {
17
17
  createFailClosedBlockingError
18
- } from "./index-y5x5wt5t.js";
18
+ } from "./index-r9y6tbbm.js";
19
19
  import {
20
20
  createWorkerShutdown
21
21
  } from "./index-54wmg4rj.js";
@@ -189,8 +189,8 @@ class PiTagHydrationError extends Error {
189
189
  this.name = "PiTagHydrationError";
190
190
  }
191
191
  }
192
- function createPiHydrationPacketConsumer(request, cached = [], byteLimit) {
193
- const assembly = createPiTagSnapshotCandidate(cached, byteLimit);
192
+ function createPiHydrationPacketConsumer(request, cached = [], byteLimit, cachedFallback = []) {
193
+ const assembly = createPiTagSnapshotCandidate(cached, byteLimit, cachedFallback);
194
194
  let sequence = 0;
195
195
  let generation;
196
196
  let busy = false;
@@ -347,7 +347,7 @@ function createPiHydrationPacketConsumer(request, cached = [], byteLimit) {
347
347
  function startPiTagSnapshotWorker(request, options = {}) {
348
348
  const entry = options.entry ?? new URL(import.meta.url.endsWith(".ts") ? "./tag-snapshot-worker-pi.ts" : "./tag-snapshot-worker-pi.js", import.meta.url);
349
349
  const started = performance.now();
350
- const consumer = createPiHydrationPacketConsumer(request, options.cached, options.byteLimit);
350
+ const consumer = createPiHydrationPacketConsumer(request, options.cached, options.byteLimit, options.cachedFallback);
351
351
  const worker = inRootAsyncContext2(() => new Worker(entry, { workerData: request }));
352
352
  const shutdown = createWorkerShutdown(worker, "pi-tag-snapshot", 1000);
353
353
  let exited = false;
@@ -567,11 +567,13 @@ function createPiTagSnapshotReader(db) {
567
567
  revisionPresent: total.present
568
568
  };
569
569
  };
570
- const ready = (sessionId) => {
570
+ const ready = (sessionId, projection) => {
571
571
  assertOutsideTransaction();
572
572
  const cached = cache.get(sessionId);
573
573
  if (!cached?.fallback)
574
574
  return false;
575
+ if (cached.projection !== projection)
576
+ return false;
575
577
  const revision = revisionReaders.get(db)?.(sessionId);
576
578
  if (!revision || cached.foreignRevision !== revision[1])
577
579
  return false;
@@ -583,17 +585,18 @@ function createPiTagSnapshotReader(db) {
583
585
  if (current?.sessionId === sessionId)
584
586
  current.cancel();
585
587
  };
586
- const load = (sessionId, kind) => inSnapshotRoot(async () => {
588
+ const load = (sessionId, kind, projection) => inSnapshotRoot(async () => {
587
589
  if (closed)
588
590
  throw new PiTagHydrationError("connection closed");
589
591
  managed.add(sessionId);
590
- if (ready(sessionId))
592
+ if (ready(sessionId, projection))
591
593
  return;
592
594
  if (current) {
593
595
  if (current.sessionId === sessionId && !current.retryable && !current.preempted) {
594
596
  if (kind === "turn")
595
597
  current.kind = "turn";
596
- return current.result;
598
+ if (current.projection === projection)
599
+ return current.result;
597
600
  }
598
601
  if (kind === "turn" && current.kind === "prewarm" && current.sessionId !== sessionId && !current.preempted) {
599
602
  current.preempted = true;
@@ -603,30 +606,36 @@ function createPiTagSnapshotReader(db) {
603
606
  await Promise.allSettled([current.result, current.released]);
604
607
  if (epoch !== (sessionEpochs.get(sessionId) ?? 0))
605
608
  throw new PiTagHydrationError("session hydration cancelled while queued", "cancelled");
606
- return load(sessionId, kind);
609
+ return load(sessionId, kind, projection);
607
610
  }
608
611
  if (failedSession === sessionId && performance.now() < failedUntil)
609
612
  throw lastFailure;
610
613
  watch.run(sessionId);
611
614
  const token = stamps(sessionId, ++jobId);
615
+ const cached = cache.get(sessionId);
616
+ if (cached && cached.projection !== projection) {
617
+ cache.delete(sessionId);
618
+ }
612
619
  const previous = cache.get(sessionId);
613
620
  const legacyFallbackOnly = previous && previous.foreignRevision === token.foreignRevision && (previous.legacyFallback || token.durableVersion - previous.durableVersion !== token.ownVersion - previous.ownVersion);
614
621
  const path = getSqliteDatabasePath2(db);
615
- const factory = workerFactories.get(db) ?? ((request, cached) => {
622
+ const factory = workerFactories.get(db) ?? ((request, cached, cachedFallback) => {
616
623
  if (!path)
617
624
  throw new PiTagHydrationError("read-only hydration requires a file-backed database");
618
- return startPiTagSnapshotWorker({ ...request, path }, { cached });
625
+ return startPiTagSnapshotWorker({ ...request, path }, { cached, cachedFallback });
619
626
  });
620
627
  const worker = factory({
621
628
  path: path ?? "",
622
629
  sessionId,
623
630
  connectionEpoch: epoch,
624
631
  sessionEpoch: token.sessionEpoch,
625
- jobId: token.jobId
626
- }, previous?.tags ?? []);
632
+ jobId: token.jobId,
633
+ projection
634
+ }, previous?.tags ?? [], previous?.fallback ?? []);
627
635
  const destination = {
628
636
  sessionId,
629
637
  kind,
638
+ projection,
630
639
  result: Promise.resolve(),
631
640
  released: worker.released,
632
641
  cancel: worker.cancel
@@ -652,6 +661,7 @@ function createPiTagSnapshotReader(db) {
652
661
  if (closed || current !== destination || !samePiTagSnapshotToken(token, live) || token.totalRevision !== live.totalRevision || generation.revision !== token.totalRevision || generation.durable !== token.durableVersion)
653
662
  throw new PiTagHydrationError("owner generation or lifetime changed", "stale");
654
663
  const snapshot = {
664
+ projection,
655
665
  firstAllocationPending: live.revisionPresent ? undefined : candidate.tags.length === 0 && !db.prepare("SELECT 1 FROM tags WHERE session_id = ? LIMIT 1").get(sessionId) ? "empty" : "legacy",
656
666
  revision: legacyFallbackOnly ? previous.revision : live.localRevision,
657
667
  foreignRevision: live.foreignRevision,
@@ -678,15 +688,19 @@ function createPiTagSnapshotReader(db) {
678
688
  }
679
689
  cache.set(sessionId, snapshot);
680
690
  }).catch((error) => {
681
- const retryable = error instanceof PiTagHydrationError && (error.code === "stale" || error.code === "cancelled");
691
+ const releaseCachedAllocations = previous && !legacyFallbackOnly && cache.get(sessionId) === previous && error instanceof PiTagHydrationError && error.message.includes("candidate memory limit exceeded");
692
+ if (releaseCachedAllocations)
693
+ cache.delete(sessionId);
694
+ const failure = releaseCachedAllocations ? new PiTagHydrationError("candidate memory limit exceeded with cached allocations; retrying without cache", "stale") : error;
695
+ const retryable = failure instanceof PiTagHydrationError && (failure.code === "stale" || failure.code === "cancelled");
682
696
  if (retryable)
683
697
  destination.retryable = true;
684
698
  if (!destination.preempted && current === destination && token.sessionEpoch === (sessionEpochs.get(sessionId) ?? 0)) {
685
699
  failedSession = sessionId;
686
- lastFailure = error;
700
+ lastFailure = failure;
687
701
  failedUntil = performance.now() + (retryable ? 0 : 500);
688
702
  }
689
- throw error;
703
+ throw failure;
690
704
  });
691
705
  Promise.allSettled([destination.result, worker.released]).then(() => {
692
706
  if (current === destination)
@@ -759,7 +773,7 @@ function createPiTagSnapshotReader(db) {
759
773
  const replacements = getTagsByNumbers2(db, sessionId, numbers);
760
774
  for (const tag of replacements)
761
775
  Object.freeze(tag);
762
- snapshot.tags = mergeChangedRows(snapshot.tags, dirty, replacements);
776
+ snapshot.tags = mergeChangedRows(snapshot.tags, dirty, snapshot.projection === "pass" ? replacements.map(projectPiPassTag) : replacements);
763
777
  snapshot.active = mergeChangedRows(snapshot.active, dirty, replacements.filter(isActive));
764
778
  if (!numbers.every(Number.isSafeInteger)) {
765
779
  snapshot.fallback = undefined;
@@ -787,7 +801,16 @@ function createPiTagSnapshotReader(db) {
787
801
  throw new PiTagHydrationError("managed snapshot read inside a transaction");
788
802
  if (!snapshot)
789
803
  return getTagsBySession2(db, sessionId);
790
- return borrowed ? snapshot.tags : snapshot.tags.map((tag) => ({ ...tag }));
804
+ if (snapshot.projection === "pass") {
805
+ const before = stamps(sessionId, 0);
806
+ const tags = getTagsBySession2(db, sessionId);
807
+ const after = stamps(sessionId, 0);
808
+ if (!samePiTagSnapshotToken(before, after) || before.totalRevision !== after.totalRevision)
809
+ throw new PiTagHydrationError("full snapshot generation changed", "stale");
810
+ return borrowed ? tags.map((tag) => Object.freeze(tag)) : tags;
811
+ }
812
+ const full = snapshot.tags;
813
+ return borrowed ? full : full.map((tag) => ({ ...tag }));
791
814
  };
792
815
  entryReaders.set(db, sync);
793
816
  fallbackReaders.set(db, (sessionId) => {
@@ -820,11 +843,28 @@ function createPiTagSnapshotReader(db) {
820
843
  });
821
844
  return read;
822
845
  }
846
+ function projectPiPassTag(tag) {
847
+ if (tag.status === "active")
848
+ return tag;
849
+ return Object.freeze({
850
+ id: tag.id,
851
+ tagNumber: tag.tagNumber,
852
+ messageId: tag.messageId,
853
+ type: tag.type,
854
+ status: tag.status,
855
+ toolOwnerMessageId: tag.toolOwnerMessageId,
856
+ tokenCount: tag.tokenCount,
857
+ toolName: tag.toolName,
858
+ dropMode: tag.dropMode
859
+ });
860
+ }
823
861
  var PI_FALLBACK_ROW_COLUMNS = "id, tag_number, type, message_id, tool_owner_message_id, entry_fingerprint";
824
862
  var PI_FALLBACK_ROW_PREDICATE = `((type = 'message' AND message_id LIKE 'pi-msg-%')
825
863
  OR (type = 'tool' AND tool_owner_message_id LIKE 'pi-msg-%'))`;
826
864
  var isActive = (tag) => tag.status === "active";
827
865
  function sameRow(left, right, keys) {
866
+ if (Object.keys(left).length !== keys.length)
867
+ return false;
828
868
  for (const key of keys)
829
869
  if (!Object.is(left[key], right[key]))
830
870
  return false;
@@ -843,11 +883,25 @@ function candidateRowBytes(row, overhead) {
843
883
  }
844
884
  return bytes;
845
885
  }
846
- function createPiTagSnapshotCandidate(cached = [], byteLimit = 128 * 1024 * 1024) {
886
+ function passTagBytes(row) {
887
+ return candidateRowBytes(row, 48 + 24 * Object.keys(row).length);
888
+ }
889
+ function createPiTagSnapshotCandidate(cached = [], byteLimit = 128 * 1024 * 1024, cachedFallback = []) {
847
890
  const tags = [];
848
891
  const active = [];
849
892
  const fallback = [];
850
- let estimatedBytes = 192;
893
+ let reusedBytes = 0;
894
+ for (const row of cached)
895
+ reusedBytes += passTagBytes(row) + 8 + (isActive(row) ? 8 : 0);
896
+ if (cached.length)
897
+ reusedBytes += 128;
898
+ for (const row of cachedFallback)
899
+ reusedBytes += candidateRowBytes(row, 192) + 8;
900
+ if (cachedFallback.length)
901
+ reusedBytes += 64;
902
+ let allocatedBytes = 192 + (cachedFallback.length ? 64 + cachedFallback.length * 48 : 0);
903
+ let estimatedBytes = reusedBytes + allocatedBytes;
904
+ const fallbackCache = cachedFallback.length && estimatedBytes <= byteLimit ? new Map(cachedFallback.map((row) => [row.id, row])) : undefined;
851
905
  let oldIndex = 0;
852
906
  let keys;
853
907
  let tagsEnded = false;
@@ -857,8 +911,9 @@ function createPiTagSnapshotCandidate(cached = [], byteLimit = 128 * 1024 * 1024
857
911
  failed = true;
858
912
  throw new Error(`Pi tag hydration: ${reason}`);
859
913
  };
860
- const admit = (row, overhead) => {
861
- estimatedBytes += candidateRowBytes(row, overhead);
914
+ const admit = (bytes) => {
915
+ allocatedBytes += bytes;
916
+ estimatedBytes = reusedBytes + allocatedBytes;
862
917
  if (estimatedBytes > byteLimit)
863
918
  reject("candidate memory limit exceeded");
864
919
  };
@@ -872,8 +927,7 @@ function createPiTagSnapshotCandidate(cached = [], byteLimit = 128 * 1024 * 1024
872
927
  const previous = tags.at(-1);
873
928
  if (previous && (previous.tagNumber > row.tagNumber || previous.tagNumber === row.tagNumber && (previous.id ?? 0) >= (row.id ?? 0)))
874
929
  reject("noncanonical tag order");
875
- admit(row, 384);
876
- keys ??= Object.keys(row);
930
+ keys = Object.keys(row);
877
931
  while (oldIndex < cached.length) {
878
932
  const old = cached[oldIndex];
879
933
  if (!old || old.tagNumber > row.tagNumber || old.tagNumber === row.tagNumber && (old.id ?? 0) >= (row.id ?? 0))
@@ -882,6 +936,7 @@ function createPiTagSnapshotCandidate(cached = [], byteLimit = 128 * 1024 * 1024
882
936
  }
883
937
  const old = cached[oldIndex];
884
938
  const selected = old && old.id === row.id && sameRow(old, row, keys) ? old : row;
939
+ admit((selected === old ? 0 : passTagBytes(row)) + 8 + (isActive(selected) ? 8 : 0));
885
940
  Object.freeze(selected);
886
941
  tags.push(selected);
887
942
  if (isActive(selected))
@@ -890,8 +945,11 @@ function createPiTagSnapshotCandidate(cached = [], byteLimit = 128 * 1024 * 1024
890
945
  appendFallback(row) {
891
946
  if (failed || fallbackEnded)
892
947
  reject("fallback packet after end or failure");
893
- admit(row, 192);
894
- fallback.push(Object.freeze(row));
948
+ const old = fallbackCache?.get(row.id);
949
+ const rowKeys = Object.keys(row);
950
+ const selected = old && Object.keys(old).length === rowKeys.length && rowKeys.every((key) => Object.is(old[key], row[key])) ? old : row;
951
+ admit((selected === old ? 0 : candidateRowBytes(row, 192)) + 8);
952
+ fallback.push(Object.freeze(selected));
895
953
  },
896
954
  end(stream) {
897
955
  if (failed)
@@ -909,7 +967,16 @@ function createPiTagSnapshotCandidate(cached = [], byteLimit = 128 * 1024 * 1024
909
967
  finish() {
910
968
  if (failed || !tagsEnded || !fallbackEnded)
911
969
  throw new Error("Pi tag hydration: incomplete candidate");
912
- return { tags, active, fallback, estimatedBytes };
970
+ if (estimatedBytes > byteLimit)
971
+ reject("candidate memory limit exceeded");
972
+ return {
973
+ tags,
974
+ active,
975
+ fallback,
976
+ estimatedBytes,
977
+ allocatedBytes,
978
+ reusedBytes
979
+ };
913
980
  }
914
981
  };
915
982
  }
@@ -961,15 +1028,24 @@ function mergeChangedRows(rows, dirty, replacements) {
961
1028
  }
962
1029
  merged.push(tag);
963
1030
  }
964
- merged.push(...replacements.slice(index));
1031
+ for (;index < replacements.length; index++) {
1032
+ const row = replacements[index];
1033
+ if (row)
1034
+ merged.push(row);
1035
+ }
965
1036
  return merged;
966
1037
  }
967
1038
  var entryReaders = new WeakMap;
968
1039
  var fallbackReaders = new WeakMap;
969
1040
  var readers = new WeakMap;
970
1041
  var revisionReaders = new WeakMap;
971
- function getPiTagSnapshotView(db, sessionId) {
972
- return createPiTagSnapshotReader(db)(sessionId, true);
1042
+ function getPiPassTagSnapshotView(db, sessionId) {
1043
+ createPiTagSnapshotReader(db);
1044
+ const snapshot = entryReaders.get(db)?.(sessionId);
1045
+ if (snapshot?.projection === "pass")
1046
+ return snapshot.tags;
1047
+ const full = snapshot?.tags ?? getTagsBySession2(db, sessionId);
1048
+ return full.map(projectPiPassTag);
973
1049
  }
974
1050
  function getPiActiveTagSnapshotView(db, sessionId, passTags) {
975
1051
  createPiTagSnapshotReader(db);
@@ -987,9 +1063,9 @@ var owners = new WeakMap;
987
1063
  var workerFactories = new WeakMap;
988
1064
  var activeJobs = new Map;
989
1065
  var waitDeadlines = new WeakMap;
990
- function prewarmPiTagSnapshot(db, sessionId) {
1066
+ function prewarmPiTagSnapshot(db, sessionId, projection) {
991
1067
  createPiTagSnapshotReader(db);
992
- owners.get(db)?.load(sessionId, "prewarm").catch(() => {});
1068
+ owners.get(db)?.load(sessionId, "prewarm", projection).catch(() => {});
993
1069
  }
994
1070
  function cancelPiTagSnapshotSession(sessionId) {
995
1071
  for (const job of activeJobs.get(sessionId) ?? [])
@@ -1005,17 +1081,17 @@ function assertPiTagSnapshotReady(db, sessionId) {
1005
1081
  createPiTagSnapshotReader(db);
1006
1082
  const owner = owners.get(db);
1007
1083
  owner?.manage(sessionId);
1008
- if (!owner?.ready(sessionId))
1084
+ if (!owner?.ready(sessionId, "pass") && !owner?.ready(sessionId))
1009
1085
  throw new PiTagHydrationError("tag snapshot is not ready; turn not sent, retry");
1010
1086
  }
1011
- function ensurePiTagSnapshotReady(db, sessionId, budget) {
1087
+ function ensurePiTagSnapshotReady(db, sessionId, budget, projection) {
1012
1088
  budget.assert();
1013
1089
  createPiTagSnapshotReader(db);
1014
1090
  const owner = owners.get(db);
1015
1091
  if (!owner)
1016
1092
  throw new PiTagHydrationError("snapshot owner unavailable");
1017
1093
  owner.manage(sessionId);
1018
- if (owner.ready(sessionId))
1094
+ if (owner.ready(sessionId, projection))
1019
1095
  return;
1020
1096
  let deadline = waitDeadlines.get(budget);
1021
1097
  if (deadline === undefined) {
@@ -1033,7 +1109,7 @@ function ensurePiTagSnapshotReady(db, sessionId, budget) {
1033
1109
  const releaseNativeWaiter = owner.addNativeWaiter(() => budget.remainingOutcome() - PI_CONTEXT_BUDGET.completionReserveMs);
1034
1110
  try {
1035
1111
  await budget.wait(Promise.race([
1036
- owner.load(sessionId, "turn"),
1112
+ owner.load(sessionId, "turn", projection),
1037
1113
  new Promise((_, reject) => {
1038
1114
  timer = setTimeout(() => reject(new PiTagHydrationError("remaining pass budget exhausted waiting for tag snapshot; turn not sent, retry", "deadline")), allowance);
1039
1115
  })
@@ -1053,4 +1129,4 @@ function ensurePiTagSnapshotReady(db, sessionId, budget) {
1053
1129
  })();
1054
1130
  }
1055
1131
 
1056
- export { PI_CONTEXT_BUDGET, PiContextDeadlineError, PiContextSupersededError, PiContextBudget, encodePiHydrationOperation, PiTagHydrationError, PI_FALLBACK_ROW_COLUMNS, PI_FALLBACK_ROW_PREDICATE, getPiTagSnapshotView, getPiActiveTagSnapshotView, readPiFallbackTagRows, prewarmPiTagSnapshot, cancelPiTagSnapshotSession, drainPiTagSnapshotSession, assertPiTagSnapshotReady, ensurePiTagSnapshotReady };
1132
+ export { PI_CONTEXT_BUDGET, PiContextDeadlineError, PiContextSupersededError, PiContextBudget, encodePiHydrationOperation, PiTagHydrationError, projectPiPassTag, PI_FALLBACK_ROW_COLUMNS, PI_FALLBACK_ROW_PREDICATE, getPiPassTagSnapshotView, getPiActiveTagSnapshotView, readPiFallbackTagRows, prewarmPiTagSnapshot, cancelPiTagSnapshotSession, drainPiTagSnapshotSession, assertPiTagSnapshotReady, ensurePiTagSnapshotReady };