@cortexkit/opencode-magic-context 0.44.2 → 0.44.3

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 (73) hide show
  1. package/dist/{conflict-warning-hook-1msyvb51.js → conflict-warning-hook-hmpzxep6.js} +3 -3
  2. package/dist/{derive-budgets-gd2270s0.js → derive-budgets-vjmvh6pz.js} +3 -1
  3. package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
  4. package/dist/features/magic-context/dreamer/hidden-single-shot.d.ts.map +1 -1
  5. package/dist/features/magic-context/dreamer/lease.d.ts +1 -1
  6. package/dist/features/magic-context/dreamer/lease.d.ts.map +1 -1
  7. package/dist/features/magic-context/memory/project-identity.d.ts +3 -0
  8. package/dist/features/magic-context/memory/project-identity.d.ts.map +1 -1
  9. package/dist/features/magic-context/message-index-async.d.ts +1 -1
  10. package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
  11. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  12. package/dist/features/magic-context/session-project-storage.d.ts +5 -5
  13. package/dist/features/magic-context/session-project-storage.d.ts.map +1 -1
  14. package/dist/features/magic-context/storage-embedding-measurements.d.ts.map +1 -1
  15. package/dist/hooks/magic-context/compartment-runner-historian.d.ts +2 -1
  16. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  17. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  18. package/dist/hooks/magic-context/compartment-runner-types.d.ts +1 -0
  19. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  20. package/dist/hooks/magic-context/derive-budgets.d.ts +4 -0
  21. package/dist/hooks/magic-context/derive-budgets.d.ts.map +1 -1
  22. package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -1
  23. package/dist/hooks/magic-context/lkg-persist.d.ts +1 -4
  24. package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/producer-window-guard.d.ts +4 -1
  26. package/dist/hooks/magic-context/producer-window-guard.d.ts.map +1 -1
  27. package/dist/hooks/magic-context/rust-mode-transform.d.ts +1 -0
  28. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/storage-busy-refusal.d.ts +6 -0
  30. package/dist/hooks/magic-context/storage-busy-refusal.d.ts.map +1 -1
  31. package/dist/{index-r9vkp4n9.js → index-33q7s9y2.js} +1 -1
  32. package/dist/{index-egkfvhms.js → index-4an2p8qa.js} +80 -14
  33. package/dist/{index-18tjha8g.js → index-638hf49n.js} +1 -1
  34. package/dist/{index-stb5fg12.js → index-9y5p0d50.js} +31 -1
  35. package/dist/{index-esxfcz5z.js → index-dgg5y7er.js} +1 -1
  36. package/dist/{index-3x9caerx.js → index-nf9sk8sh.js} +3 -3
  37. package/dist/{index-gtzcmv90.js → index-q5p1aqvv.js} +5 -5
  38. package/dist/{index-40s1xz22.js → index-rdsaxnf2.js} +1 -1
  39. package/dist/{index-ttdn47aq.js → index-yhm60r53.js} +134 -49
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +453 -226
  42. package/dist/plugin/dream-timer.d.ts.map +1 -1
  43. package/dist/plugin/embedding-bootstrap.d.ts.map +1 -1
  44. package/dist/plugin/messages-transform.d.ts.map +1 -1
  45. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  46. package/dist/{read-session-chunk-wmvgnd24.js → read-session-chunk-n072mcq4.js} +2 -2
  47. package/dist/{recomp-orchestrator-rk40ff15.js → recomp-orchestrator-19tr6zya.js} +6 -6
  48. package/dist/{send-session-notification-6xsrcxnp.js → send-session-notification-04hvd54c.js} +2 -2
  49. package/dist/shared/run-token-log.d.ts +13 -0
  50. package/dist/shared/run-token-log.d.ts.map +1 -0
  51. package/dist/shared/sqlite.d.ts +7 -0
  52. package/dist/shared/sqlite.d.ts.map +1 -1
  53. package/dist/{transform-postprocess-phase-t7xgdhdf.js → transform-postprocess-phase-z2mfc5w1.js} +6 -6
  54. package/dist/v2/hidden-completion.d.ts +7 -1
  55. package/dist/v2/hidden-completion.d.ts.map +1 -1
  56. package/dist/v2/hooks/context.d.ts.map +1 -1
  57. package/dist/v2/hooks/hidden-terminal-error.d.ts +8 -0
  58. package/dist/v2/hooks/hidden-terminal-error.d.ts.map +1 -0
  59. package/dist/v2/hooks/tools.d.ts +1 -1
  60. package/dist/v2/hooks/tools.d.ts.map +1 -1
  61. package/dist/v2/server.js +584 -153
  62. package/dist/{wrapup-orchestrator-h8tr10c6.js → wrapup-orchestrator-sy4m56a7.js} +7 -7
  63. package/package.json +1 -1
  64. package/src/config/latch-permanence-guard.test.ts +4 -0
  65. package/src/shared/data-path.test.ts +1 -1
  66. package/src/shared/models-dev-cache.test.ts +30 -1
  67. package/src/shared/run-token-log.test.ts +65 -0
  68. package/src/shared/run-token-log.ts +39 -0
  69. package/src/shared/sqlite-acquisition-routing.test.ts +19 -11
  70. package/src/shared/sqlite-pass-scope.test.ts +115 -144
  71. package/src/shared/sqlite.ts +123 -20
  72. package/src/shared/storage-busy.test.ts +34 -57
  73. package/src/shared/write-transaction-attribution.test.ts +13 -11
@@ -270,7 +270,10 @@ function installTransactionRouting(db, readonly) {
270
270
  writable: true,
271
271
  value: (sql) => {
272
272
  if (/^\s*BEGIN\s+(?:IMMEDIATE|EXCLUSIVE)(?:\s+TRANSACTION)?\s*;?\s*$/i.test(sql)) {
273
- retryAcquisition(() => nativeExec(sql), sql.trim());
273
+ if (transformPassScope.getStore()?.active || backgroundWriterScope.getStore())
274
+ acquireShort(db, () => nativeExec(sql), sql.trim());
275
+ else
276
+ nativeExec(sql);
274
277
  return db;
275
278
  }
276
279
  return nativeExec(sql);
@@ -454,6 +457,11 @@ function getSqliteMemoryStats() {
454
457
  }
455
458
  var privilegeDepth = new WeakMap;
456
459
  var transformPassScope = new AsyncLocalStorage;
460
+ var admissionScope = new AsyncLocalStorage;
461
+ var backgroundWriterScope = new AsyncLocalStorage;
462
+ function withSqliteBackgroundWriter(operation) {
463
+ return backgroundWriterScope.run(true, operation);
464
+ }
457
465
  function withSqliteTransformPass(operation) {
458
466
  const lease = { active: true };
459
467
  return transformPassScope.run(lease, () => {
@@ -486,27 +494,79 @@ class SqliteAcquisitionBusyError extends Error {
486
494
  code = "SQLITE_BUSY";
487
495
  stage;
488
496
  constructor(cause, stage = "BEGIN IMMEDIATE") {
489
- super("SQLite writer acquisition remained busy after 3 attempts", { cause });
497
+ super("SQLite writer acquisition remained busy", { cause });
490
498
  this.name = "SqliteAcquisitionBusyError";
491
499
  this.stage = stage;
492
500
  }
493
501
  }
494
- function retryAcquisition(acquire, stage) {
495
- if (!transformPassScope.getStore()?.active) {
502
+ var SHORT_BUSY_TIMEOUT_MS = 25;
503
+ var FOREGROUND_IN_PASS_BUSY_TIMEOUT_MS = 250;
504
+ var FOREGROUND_ACQUISITION_BUDGET_MS = 16500;
505
+ function acquireShort(db, acquire, site) {
506
+ const started = performance.now();
507
+ const previous = pragmaNumber(db, "busy_timeout");
508
+ let acquired = false;
509
+ try {
510
+ const timeout = transformPassScope.getStore()?.active && !admissionScope.getStore() && !backgroundWriterScope.getStore() ? FOREGROUND_IN_PASS_BUSY_TIMEOUT_MS : SHORT_BUSY_TIMEOUT_MS;
511
+ db.exec(`PRAGMA busy_timeout=${timeout}`);
496
512
  acquire();
497
- return;
513
+ acquired = true;
514
+ } catch (error) {
515
+ if (transformPassScope.getStore()?.active && isTransientSqliteError(error))
516
+ throw new SqliteAcquisitionBusyError(error, site);
517
+ throw error;
518
+ } finally {
519
+ if (previous !== null)
520
+ db.exec(`PRAGMA busy_timeout=${previous}`);
521
+ const elapsed = performance.now() - started;
522
+ if (elapsed >= 250)
523
+ console.warn(`[${new Date().toISOString()}] [magic-context] sqlite acquisition site=${site} lane=${transformPassScope.getStore()?.active ? "foreground" : "background"} elapsed=${Math.round(elapsed)}ms attempts=1 outcome=${acquired ? "acquired" : "busy"}`);
498
524
  }
499
- const delays = [500, 1000];
500
- for (let attempt = 0;; attempt++) {
525
+ }
526
+ async function beginSqliteWriterAsync(db, site) {
527
+ const started = performance.now();
528
+ let attempts = 0;
529
+ for (;; ) {
530
+ attempts++;
501
531
  try {
502
- acquire();
532
+ withSqliteBackgroundWriter(() => db.exec("BEGIN IMMEDIATE"));
533
+ const elapsed = performance.now() - started;
534
+ if (elapsed >= 250)
535
+ console.warn(`[${new Date().toISOString()}] [magic-context] sqlite acquisition site=${site} lane=background elapsed=${Math.round(elapsed)}ms attempts=${attempts} outcome=acquired`);
503
536
  return;
504
537
  } catch (error) {
505
- if (error instanceof SqliteAcquisitionBusyError || !isTransientSqliteError(error))
538
+ if (!isTransientSqliteError(error))
539
+ throw error;
540
+ const elapsed = performance.now() - started;
541
+ if (elapsed >= FOREGROUND_ACQUISITION_BUDGET_MS) {
542
+ console.warn(`[${new Date().toISOString()}] [magic-context] sqlite acquisition site=${site} lane=background elapsed=${Math.round(elapsed)}ms attempts=${attempts} outcome=busy`);
506
543
  throw error;
507
- if (attempt === delays.length)
508
- throw new SqliteAcquisitionBusyError(error, stage);
509
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delays[attempt]);
544
+ }
545
+ await new Promise((resolve) => setTimeout(resolve, Math.min(attempts === 1 ? 500 : 1000, FOREGROUND_ACQUISITION_BUDGET_MS - elapsed)));
546
+ }
547
+ }
548
+ }
549
+ async function withAsyncPrivilegedWriter(db, operation) {
550
+ const started = performance.now();
551
+ let attempts = 0;
552
+ for (;; ) {
553
+ attempts++;
554
+ try {
555
+ const result = admissionScope.run(true, () => withSqliteTransformPass(() => withPrivilegedWriter(db, operation)));
556
+ const elapsed = performance.now() - started;
557
+ if (elapsed >= 250)
558
+ console.warn(`[${new Date().toISOString()}] [magic-context] sqlite acquisition site=privileged_writer lane=foreground elapsed=${Math.round(elapsed)}ms attempts=${attempts} outcome=acquired`);
559
+ return result;
560
+ } catch (error) {
561
+ if (!(error instanceof SqliteAcquisitionBusyError))
562
+ throw error;
563
+ const elapsed = performance.now() - started;
564
+ if (elapsed >= FOREGROUND_ACQUISITION_BUDGET_MS) {
565
+ if (elapsed >= 250)
566
+ console.warn(`[${new Date().toISOString()}] [magic-context] sqlite acquisition site=privileged_writer lane=foreground elapsed=${Math.round(elapsed)}ms attempts=${attempts} outcome=busy`);
567
+ throw error instanceof SqliteAcquisitionBusyError ? error : new SqliteAcquisitionBusyError(error);
568
+ }
569
+ await new Promise((resolve) => setTimeout(resolve, Math.min(attempts === 1 ? 500 : 1000, FOREGROUND_ACQUISITION_BUDGET_MS - elapsed)));
510
570
  }
511
571
  }
512
572
  }
@@ -522,7 +582,13 @@ function withPrivilegedWriter(db, operation) {
522
582
  if (nested) {
523
583
  db.exec(`SAVEPOINT ${savepoint}`);
524
584
  } else {
525
- retryAcquisition(() => db.exec("BEGIN IMMEDIATE"), "BEGIN IMMEDIATE");
585
+ try {
586
+ db.exec("BEGIN IMMEDIATE");
587
+ } catch (error) {
588
+ if (transformPassScope.getStore()?.active && isTransientSqliteError(error))
589
+ throw new SqliteAcquisitionBusyError(error);
590
+ throw error;
591
+ }
526
592
  }
527
593
  privilegeDepth.set(db, previousDepth + 1);
528
594
  try {
@@ -987,4 +1053,4 @@ function findLastAssistantModelFromOpenCodeDb(sessionId) {
987
1053
  }
988
1054
  }
989
1055
 
990
- export { resolveOpenCodeDbPath, hasV1MessageTables, assertOpenCodeStoreGeneration, openCodeDbPathExists, getOpenCodeDbProbeDescriptions, formatOpenCodeDbMissingBanner, formatOpenCodeDbMissingStatusLine, formatOpenCodeDbReadFailureStatusLine, recordOpenCodeDbReadFailure, clearOpenCodeDbReadFailure, getOpenCodeDbReadFailure, claimOpenCodeDbDiagnosticOnce, registerSlowWriteReporter, detectSqliteRuntime, Database, getSqliteMemoryStats, withSqliteTransformPass, withoutSqliteTransformPass, isTransientSqliteError, SqliteAcquisitionBusyError, withPrivilegedWriter, closeQuietly, openCodeDbExists, withReadOnlySessionDb, getRawSessionMessageCountFromDb, observeOpenCodeTurnEvent, clearTrackedOpenCodeSession, assistantAwaitingTools, shouldHoldIgnoredNotification, latestPersistedMessageForRecovery, getMessageTimesFromOpenCodeDb, findLastAssistantModelFromOpenCodeDb };
1056
+ export { resolveOpenCodeDbPath, hasV1MessageTables, assertOpenCodeStoreGeneration, openCodeDbPathExists, getOpenCodeDbProbeDescriptions, formatOpenCodeDbMissingBanner, formatOpenCodeDbMissingStatusLine, formatOpenCodeDbReadFailureStatusLine, recordOpenCodeDbReadFailure, clearOpenCodeDbReadFailure, getOpenCodeDbReadFailure, claimOpenCodeDbDiagnosticOnce, registerSlowWriteReporter, detectSqliteRuntime, Database, getSqliteMemoryStats, withSqliteBackgroundWriter, withSqliteTransformPass, withoutSqliteTransformPass, isTransientSqliteError, SqliteAcquisitionBusyError, beginSqliteWriterAsync, withAsyncPrivilegedWriter, withPrivilegedWriter, closeQuietly, openCodeDbExists, withReadOnlySessionDb, getRawSessionMessageCountFromDb, observeOpenCodeTurnEvent, clearTrackedOpenCodeSession, assistantAwaitingTools, shouldHoldIgnoredNotification, latestPersistedMessageForRecovery, getMessageTimesFromOpenCodeDb, findLastAssistantModelFromOpenCodeDb };
@@ -3,7 +3,7 @@ import {
3
3
  } from "./index-3bygzk2d.js";
4
4
  import {
5
5
  sendStatusNotification2
6
- } from "./index-r9vkp4n9.js";
6
+ } from "./index-33q7s9y2.js";
7
7
  import {
8
8
  readJsoncFile
9
9
  } from "./index-sd3egckz.js";
@@ -787,6 +787,21 @@ function getSdkOutputLimit(providerID, modelID) {
787
787
  loadPersistedApiCacheOnce();
788
788
  return lookupMetadataWithTagFallback(apiCache, providerID, modelID)?.outputLimit;
789
789
  }
790
+ function getSdkInputLimit(providerID, modelID) {
791
+ loadPersistedApiCacheOnce();
792
+ if (!apiCache)
793
+ return;
794
+ const direct = apiCache.get(`${providerID}/${modelID}`)?.inputLimit;
795
+ if (isSaneLimit(direct))
796
+ return direct;
797
+ const colon = modelID.indexOf(":");
798
+ if (colon > 0) {
799
+ const tagless = apiCache.get(`${providerID}/${modelID.slice(0, colon)}`)?.inputLimit;
800
+ if (isSaneLimit(tagless))
801
+ return tagless;
802
+ }
803
+ return;
804
+ }
790
805
  function lookupMetadataWithTagFallback(cache, providerID, modelID) {
791
806
  if (!cache)
792
807
  return;
@@ -842,6 +857,21 @@ function resolveKnownHistorianContextLimit2(historianModelOverride) {
842
857
  const limit = getSdkContextLimit(providerID, modelID, undefined, { reservation: "none" });
843
858
  return typeof limit === "number" && limit > 0 ? limit : undefined;
844
859
  }
860
+ function resolveHistorianProducerLimits2(modelKey) {
861
+ if (!modelKey?.includes("/"))
862
+ return {};
863
+ const [provider, ...parts] = modelKey.split("/");
864
+ const model = parts.join("/");
865
+ if (!provider || !model)
866
+ return {};
867
+ const input = getSdkInputLimit(provider, model);
868
+ const window = getSdkWindowGeometry(provider, model)?.derivation.window;
869
+ const context = window ?? (input === undefined ? resolveKnownHistorianContextLimit2(modelKey) : undefined);
870
+ return {
871
+ ...context !== undefined ? { context } : {},
872
+ ...input !== undefined ? { input } : {}
873
+ };
874
+ }
845
875
  function resolveHistorianContextLimit2(historianModelOverride) {
846
876
  if (typeof historianModelOverride === "string" && historianModelOverride.includes("/")) {
847
877
  return resolveKnownHistorianContextLimit2(historianModelOverride) ?? DEFAULT_HISTORIAN_CONTEXT_FALLBACK;
@@ -857,4 +887,4 @@ function producerSourceLocalBudget2(providerTokens, modelKey) {
857
887
  return ratio === 1 ? providerTokens : localBudget(providerTokens, ratio);
858
888
  }
859
889
 
860
- export { canonicalModelIdentity, piModelRefToCanonical, modelRefLookupOrder, setStoragePrivatePermissionEnforcement, shouldEnforcePrivateStoragePermissions, catalogOutputReserve, setWindowOverlayPath, reloadWindowOverlay, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, isSaneLimit, setOutputReserveConfig, resolveLimit, refreshModelLimitsFromApi, refreshModelLimitsAfterAuthOnce, getSdkWindowGeometry, getSdkContextLimit, modelSupportsVision, getSdkOutputLimit, getModelsDevCacheState, deriveTriggerBudget2, deriveHistorianChunkTokens2, resolveKnownHistorianContextLimit2, resolveHistorianContextLimit2, producerSourceLocalBudget2 };
890
+ export { canonicalModelIdentity, piModelRefToCanonical, modelRefLookupOrder, setStoragePrivatePermissionEnforcement, shouldEnforcePrivateStoragePermissions, catalogOutputReserve, setWindowOverlayPath, reloadWindowOverlay, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, isSaneLimit, setOutputReserveConfig, resolveLimit, refreshModelLimitsFromApi, refreshModelLimitsAfterAuthOnce, getSdkWindowGeometry, getSdkContextLimit, modelSupportsVision, getSdkOutputLimit, getModelsDevCacheState, deriveTriggerBudget2, deriveHistorianChunkTokens2, resolveKnownHistorianContextLimit2, resolveHistorianProducerLimits2, resolveHistorianContextLimit2, producerSourceLocalBudget2 };
@@ -6,7 +6,7 @@ import {
6
6
  withReadOnlySessionDb,
7
7
  getRawSessionMessageCountFromDb,
8
8
  getMessageTimesFromOpenCodeDb
9
- } from "./index-egkfvhms.js";
9
+ } from "./index-4an2p8qa.js";
10
10
  import {
11
11
  UNKNOWN_FIT_RATIO,
12
12
  resolveDecisionCalibration,
@@ -21,17 +21,17 @@ import {
21
21
  getActiveCompartmentRun,
22
22
  markActiveCompartmentRunPublished,
23
23
  registerActiveCompartmentRun
24
- } from "./index-ttdn47aq.js";
24
+ } from "./index-yhm60r53.js";
25
25
  import {
26
26
  pushNotification2
27
27
  } from "./index-jdxxq8cz.js";
28
28
  import {
29
29
  sendStatusNotification2
30
- } from "./index-r9vkp4n9.js";
30
+ } from "./index-33q7s9y2.js";
31
31
  import {
32
32
  setRecompStarting2,
33
33
  setRecompTerminal2
34
- } from "./index-40s1xz22.js";
34
+ } from "./index-rdsaxnf2.js";
35
35
 
36
36
  // src/hooks/magic-context/wrapup-orchestrator.ts
37
37
  import * as crypto from "node:crypto";
@@ -9,7 +9,7 @@ import {
9
9
  openCodeDbExists,
10
10
  withReadOnlySessionDb,
11
11
  getMessageTimesFromOpenCodeDb
12
- } from "./index-egkfvhms.js";
12
+ } from "./index-4an2p8qa.js";
13
13
  import {
14
14
  BoundedSessionMap,
15
15
  resolveWorkspaceShareCategories,
@@ -117,7 +117,7 @@ import {
117
117
  peekNoteNudgeText,
118
118
  markNoteNudgeDelivered,
119
119
  getActiveCompartmentRun
120
- } from "./index-ttdn47aq.js";
120
+ } from "./index-yhm60r53.js";
121
121
  import {
122
122
  textMentionsRecentCommit,
123
123
  hasMeaningfulUserText2,
@@ -182,13 +182,13 @@ import {
182
182
  extractToolCallObservation,
183
183
  ToolMutationBatch,
184
184
  createToolDropTarget
185
- } from "./index-esxfcz5z.js";
185
+ } from "./index-dgg5y7er.js";
186
186
  import {
187
187
  canonicalModelIdentity
188
- } from "./index-stb5fg12.js";
188
+ } from "./index-9y5p0d50.js";
189
189
  import {
190
190
  getErrorMessage
191
- } from "./index-r9vkp4n9.js";
191
+ } from "./index-33q7s9y2.js";
192
192
  import {
193
193
  logSlowWriteTransaction
194
194
  } from "./index-kr5qehbd.js";
@@ -4,7 +4,7 @@ import {
4
4
  clearEmergencyRecovery,
5
5
  dropSlot,
6
6
  executeContextRecomp
7
- } from "./index-ttdn47aq.js";
7
+ } from "./index-yhm60r53.js";
8
8
  import {
9
9
  sessionLog
10
10
  } from "./index-3bygzk2d.js";